Cow IDs
Time Limit: 3000/1000MS (Java/Others) Memory Limit: 65535/65535KB (Java/Others)
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 (
1≤K≤10
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 (
1≤N≤107
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
#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;
}