Description
TICers all like Binary numbers. They want to know the Kth(K <= 10000000) binary numbers whose sum of all ‘1’ digits is N(N <= 10). The leading bit of each label is always a "1" bit, of course.
Input
There are several test cases
The first line, an integer T indicates the test cases.
Next T lines, two integers K, N as mentioned above.
Output
Output the Kth number in the binary number form.
Sample Input
1
7 3
Sample Output
10110
解题思路:
顺序找第m个含有n个1的二进制数
考虑一个i位的二进制数,含有n个1就有C(i,n)中可能性,如果C(i,n)<m,那么肯定不止i位,所以我们找到第一个i使得C(i,n)>=m,那么第i位就是这个数的最高位,而且问题可以转化为寻找第m-C(i-1,n)个n-1个1的数,同样一直处理即可
#include <iostream>
using namespace std;
int ans[5000],c[5000][11],m,n;
int main()
{
c[0][0]=1;
for (int i=1; i<5000; i++)
{
c[i][0]=1;
for (int j=1; j<=10; j++) c[i][j]=c[i-1][j]+c[i-1][j-1];
}
cin>>m;
while (cin>>m>>n)
{
if (n==1)
{
cout<<1;
for (int i=0; i<m-1; i++) cout<<0;
cout<<endl;
continue;
}
int flag=0;
for (int i=0; i<5000; i++) ans[i]=0;
for (int i=n; i>0; i--)
{
int j=1;
while (c[j][i]<m) j++;
if (flag==0) flag=j;
ans[j-1]=1;
m-=c[j-1][i];
}
for (int i=flag-1; i>=0; i--) cout<<ans[i];
cout<<endl;
}
}
最后欢迎大家访问我的个人网站: 1024s