マイクロソフト2014実習生オンラインテストK-th string


問題の説明:
Time Limit: 10000ms Case Time Limit: 1000ms Memory Limit: 256MB Description 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. Input 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. 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
基本的な考え方:
簡単な点はK番目の数を探し続けることですが、時間の複雑さが高いです.O((M+N)*K)
ここでは配列組合せ思想を用いる.時間複雑度O((M+N)*log(M))
まず、どれだけの可能性があるかを分析します.つまり、Impossibleを排除します.全部でM+Nビットの数字で、M個の'1'は、この数より大きいKはすべて合法ではない可能性があります.
そして結果を高位から低位まで分析し,1位が「0」であれば,残りの数字にはM個の「1」,N−1個の0があり,共有可能である.
  • K
  • K>k_maxでは1位が'1',K=K-k_max
  • K=k_maxでは、前Mビットはいずれも′1′であり、残りのNビットは′0′
  • である.
    このようにして、コードが得られ、コード中のMは0を表し、Nは1の個数を表す.
    #include <iostream>
    #include <algorithm>
    #include <cmath>
    using namespace std;
    
    long long int cc(int n, int k){
    	double biggest_seq = 1 ;
    	for ( int i = 0 ; i < k ; i ++) {
    		biggest_seq *= ((double)n-i)/(k-i) ;
    	}
    	return floor(biggest_seq+0.0002);
    }
    
    int main()
    {
    	int count = 0 ;
    	cin >> count;
    	int n, m, seq ;
    	while ( count --) {
    		cin >> m >> n >> seq;
    		unsigned int biggest = 0;
    		unsigned int smallest = 0;
    		long long int biggest_seq = 1 ;
    		char *ch = new char[m+n+1];
    		int ch_count = 0;
    		ch[m+n] = '\0';
    		
    		biggest_seq = cc(m+n, m) ;
    		if ( biggest_seq < seq  ) {
    			cout << "Impossible
    "; continue; } int i, j; for ( i = 1, j = 0; i <= m && j < n ; ) { // if the highest value is 1 biggest_seq = cc(m-i+n-j, m-i) ; //cout << biggest_seq << ' ' << seq << ' '; if ( biggest_seq > seq ) { ch[ch_count++] = '0'; i ++; } else if ( biggest_seq < seq ) { ch[ch_count++] = '1'; seq -= biggest_seq; j ++; } else if ( biggest_seq == seq ) { ch[ch_count++] = '0'; while ( j < n ) { ch[ch_count++] = '1'; j ++; } while ( i < m ) { ch[ch_count++] = '0'; i ++; } } } while ( j < n ) { ch[ch_count++] = '1'; j ++; } while ( ch_count < m+n ) { ch[ch_count++] = '0'; i ++; } cout << ch << endl; } }