微软面试:k-th string

来源:互联网 发布:php cookie 登陆 编辑:程序博客网 时间:2024/04/28 01:32

问题:

Consider a string set that each of them consists of {0, 1} only. All strings in the set have the same number of 0s and 1s. Write a program to find and output the K-th string according to the dictionary order. If s​uch a string doesn’t exist, or the input is not valid, please output “Impossible”. For example, if we have two ‘0’s and two ‘1’s, we will have a set with 6 different strings, {0011, 0101, 0110, 1001, 1010, 1100}, and the 4th string is 1001.


输入
The first line of the input file contains a single integer t (1 ≤ t ≤ 10000), the number of test cases, followed by the input data for each test case.
Each test case is 3 integers separated by blank space: N, M(2 <= N + M <= 33 and N , M >= 0), K(1 <= K <= 1000000000). N stands for the number of ‘0’s, M stands for the number of ‘1’s, and K stands for the K-th of string in the set that needs to be printed as output.

输出
For each case, print exactly one line. If the string exists, please print it, otherwise print “Impossible”.


Sample In
3
2 2 2
2 2 7
4 7 47


Sample Out
0101
Impossible
01010111011

思路:

1:根据0、1个数(num0,num1),计算排列组合数maxn

2:计算组合中的最小值和最大值。

3:从最小值遍历到最大值,统计每个数的二进制的1的个数,判断该数是否合法。合法则kth++。

4:kth=findn时,把该数转换成二进制输出。

源代码:

#include<iostream>#include<cmath>using namespace std;bool isLegal(int v,int num1){int num=0;while(v){v&=(v-1);num++;}if(num==num1)return true;return false;}void numToBinary(int n,int allnum){int i=0;bool a[1000];for(i=0;i<allnum;i++)a[i]=0;i=0;while(1){a[i]=n%2;n=n/2;if(n==0)break;i++;}    for(int j=allnum-1; j>=0; j--)    cout<<a[j];}int main(){int n,num0,num1,findn; //0的数量,1的数量,查找第n个数字 int allnum,maxn,upnum,lownum;//01个数,数量的最大值,最大值,最小值。 cin>>n;while(n>0){cin>>num0>>num1>>findn;allnum=num0+num1;int n_Multiply=1,k_Multiply=1;for(int i=0;i<num0;i++){n_Multiply*=(allnum-i);k_Multiply*=(num0-i);}maxn=n_Multiply/k_Multiply; //maxnif(findn>maxn){cout<<"Impossible"<<endl;n--;continue;//continue}lownum=pow(2,num1)-1;upnum=pow(2,allnum)-1-lownum;//cout<<lownum<<" "<<upnum<<endl;//int nth=0;int loopn;for(loopn=lownum;loopn<=upnum;loopn++){if(isLegal(loopn,num1)){//cout<<loopn<<"is legal"<<endl;nth++;}else continue;if(nth==findn){numToBinary(loopn,allnum);break;//break}}n--;}//while}


0 0
原创粉丝点击