描述
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‘.
输入
A single line with three space separated integers: N, L, and I.
输出
A single line containing the integer that represents the Ith element from the order set, as described.
样例输入
5 3 19
样例输出
10011
题意
N位的二进制串,从小到大排序,问‘1‘的个数<=L的第I个串。
题解
采用逐位确定法,如果要第N位填上‘1‘,那么前N-1位<=L的串的个数<=I。
那么如何确定前N-1位<=L的串的个数呢?
dp[i][j]代表第i位填了j个‘1‘的串的个数,
当第i位填‘1‘,那么就有dp[i-1][j-1]。
当第i位填‘0’,那么就有dp[i-1][j]。
代码
1 #include<bits/stdc++.h> 2 using namespace std; 3 #define ll long long 4 ll dp[32][32],I; 5 int main() 6 { 7 int N,L; 8 cin>>N>>L>>I; 9 dp[0][0]=1; 10 for(int i=1;i<=N;i++) 11 for(int j=0;j<=L;j++) 12 if(j==0)dp[i][j]=dp[i-1][j]; 13 else if(j>i)dp[i][j]=dp[i][i]; 14 else if(j==i)dp[i][j]=dp[i][j-1]+1; 15 else dp[i][j]=dp[i-1][j]+dp[i-1][j-1]; 16 for(int i=N-1;i>=1;i--) 17 if(dp[i][L]<I){cout<<"1";I-=dp[i][L--];} 18 else cout<<"0"; 19 if(I!=1)cout<<"1"; 20 else cout<<"0"; 21 return 0; 22 }
原文:https://www.cnblogs.com/taozi1115402474/p/11673116.html