UESTC 548 Cow IDs (二进制的排列 组合数 STL)

Cow IDs

Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others)
Submit  Status

Being a secret computer geek, Farmer John labels all of his cows with binary numbers. However, he is a bit superstitious, and only labels cows with binary numbers that have exactly  K K 1 bits ( 1K10 1≤K≤10). The leading bit of each label is always a 1 bit, of course. FJ assigns labels in increasing numeric order, starting from the smallest possible valid label -- a  K K-bit number consisting of all 1 bits. Unfortunately, he loses track of his labeling and needs your help: please determine the  Nth Nth label he should assign ( 1N107 1≤N≤107).

Input

  • Line  1 1: Two space-separated integers,  N N and  K K.

Output

  • Line  1 1: Output the  Nth Nth label he should assign

Sample input and output

Sample Input Sample Output
7 3
10110

Source

USACO Feb 2012

大体题意:
给你N 和K ,让你求一个二进制数,包含K个1,其余只能是0,求第N小的数!

思路:
先求出此时的N和K时,有多少个0 有多少1组成,N不断的减,(最后N的意义就是在当前0和当前1的数第几个小的)然后构建一个最小的数,比如说有3个1 和2 个0 组成吧,那么最小的数就是10011,然后利用next_permutation函数求n次即可!
最后,输出字符串即可!

注意:
数组要开大点,100W差不多就可以了!
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1000000 + 10;
char s[maxn];
int main(){
	int n,k,m=0;
	scanf("%d%d",&n,&k);
	int star = 1;
	for ( ; n > star ; ++m){
		n-=star;
		star = star * (k+m)/(m+1);
	}
	s[0]='1';
	for (int i = 1; i < k + m; ++i){
		if (i <= m)s[i]='0';
		else s[i] = '1';
	}
	s[k+m]=0;
	while(--n && next_permutation(s+1,s+k+m));
	printf("%s\n",s);
	return 0;
}


你可能感兴趣的:(二进制,C语言,STL)