腾讯举办的一场比赛——1007. Binary Numbers

来源:互联网 发布:百度派 知乎 编辑:程序博客网 时间:2024/06/15 13:50
题目描述
XDTICers all like Binary numbers. They want to know the Kth(K <= 10000000) binary numbers whose sum of all ‘1’ digits is N(N <= 10).
输入
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 the Kth number in the binary number form.
样例输入
1
7 3
样例输出
10110

此题显然就是全排列的思想。
但是因为K值太大,不能一开始就全排列,否则会超时。
那么我们先剪枝。
找找规律发现,当K值和N值一定时,那么一共的可能种数是S=C(N-1)(N-1)+C(N-1)(N)+C(N-1)(N+1)+...。
所以当我们的S快接近K值(S要小于K),那么再开始对那时候的情况排列组合。

以下是我AC的代码。

#include <set>
#include <map>
#include <list>
#include <stack>
#include <queue>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iomanip>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;

int pa[100];

int pl(int a, int b)
{
int ss = 1;
for (int i = 0; i < a; i++)
{
ss = ss * (b - a + i + 1) / (i + 1);
}
return ss;
}

int main()
{
int t;

scanf("%d", &t);
while (t--)
{
int k, n;
scanf("%d%d", &k, &n);
if (n == 1)
{
printf("1");
for (int i = 0; i < k - 1; i++)
{
printf("0");
}
printf("\n");
continue;
}
int s = 1;
int p = 0;
while (1)
{
int t = pl(n - 1, n + p);
if (s + t > k) break;
s += t;
p++;
}
p += n;
for (int i = 0; i <= p - n; i++)
{
pa[i] = 0;
}
for (int i = p - n + 1; i < p; i++)
{
pa[i] = 1;
}
while (1)
{
s++;
if (s == k)
{
printf("1");
for (int i = 0; i < p; i++)
{
printf("%d", pa[i]);
}
printf("\n");
break;
}
next_permutation(pa, pa + p);
}
}

return 0;
}



0 0
原创粉丝点击