一 原题
Kim Schrijvers
Consider an ordered set S of strings of N (1 <= N <= 31) bits. Bits, of course, are either 0 or 1.
This set of strings is interesting because it is ordered and contains all possible strings of length N that have L (1 <= L <= N) or fewer bits that are `1'.
Your task is to read a number I (1 <= I <= sizeof(S)) from the input and print the Ith element of the ordered set for N bits with no more than L bits that are `1'.
PROGRAM NAME: kimbits
INPUT FORMAT
A single line with three space separated integers: N, L, and I.SAMPLE INPUT (file kimbits.in)
5 3 19
OUTPUT FORMAT
A single line containing the integer that represents the Ith element from the order set, as described.SAMPLE OUTPUT (file kimbits.out)
10011
二 分析
一开始怀着侥幸心理想通过判断每个数里有多少个1,从1开始枚举到答案。但是数据有一个点是找第(INT_MAX+1)个数。。(也就是说变量I要定义成long long,因为这个又WA了好几次啊。。)正确做法是先动态规划求出长度为N的01串里含有至少L个1的串个数。然后依次判断目标串里每一位是填1还是0。
三 代码
运行结果:
USER: Qi Shen [maxkibb3] TASK: kimbits LANG: C++ Compiling... Compile: OK Executing... Test 1: TEST OK [0.000 secs, 4188 KB] Test 2: TEST OK [0.000 secs, 4188 KB] Test 3: TEST OK [0.000 secs, 4188 KB] Test 4: TEST OK [0.000 secs, 4188 KB] Test 5: TEST OK [0.000 secs, 4188 KB] Test 6: TEST OK [0.000 secs, 4188 KB] Test 7: TEST OK [0.000 secs, 4188 KB] Test 8: TEST OK [0.000 secs, 4188 KB] Test 9: TEST OK [0.000 secs, 4188 KB] Test 10: TEST OK [0.000 secs, 4188 KB] Test 11: TEST OK [0.000 secs, 4188 KB] Test 12: TEST OK [0.000 secs, 4188 KB] Test 13: TEST OK [0.000 secs, 4188 KB] All tests OK.
Your program ('kimbits') produced all correct answers! This is your submission #6 for this problem. Congratulations!
AC代码:
/*
ID:maxkibb3
LANG:C++
PROG:kimbits
*/
#include<cstdio>
const int MAX_N = 31;
int N, L;
long long I;
long long dp[MAX_N + 1][MAX_N + 1];
int main() {
freopen("kimbits.in", "r", stdin);
freopen("kimbits.out", "w", stdout);
scanf("%d%d%lld", &N, &L, &I);
dp[0][0] = 1;
for(int i = 1; i <= N; i++) {
for(int j = 0; j <= L; j++) {
if(j == 0)
dp[i][j] = dp[i - 1][j];
else if(j > i)
dp[i][j] = dp[i][i];
else if(j == i)
dp[i][j] = dp[i][j - 1] + 1;
else
dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1];
}
}
for(int i = 1; i < N; i++) {
if(I <= dp[N - i][L]) {
printf("0");
}
else {
printf("1");
I -= dp[N - i][L];
L--;
}
}
if(I == 1) printf("0");
else printf("1");
printf("\n");
return 0;
}