微軟2014實習生及秋令營技術類職位在線測試之 2. K-th String

題目2 : K-th string

時間限制:10000ms
單點時限:1000ms
內存限制: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 such 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”.


樣例輸入
3
2 2 2
2 2 7
4 7 47
樣例輸出
0101
Impossible
0101011101



解題思路:

對於任何一個0*1*0*1*... 串, 能夠給出下一個升序的排列的項。關鍵是設計出一個move的函數,對於當前任何一個串,能夠得出其下一個的01字符串是什麼。具體如何移動/交換字符串中的01位置,詳見代碼。


#include <iostream>
#include <cstdio> //包含語言重定向函數freopen的庫
#include <vector>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
void swap(int &a, int &b){
	int temp=a;
	a = b;
	b = temp;
}
long long jiecheng(long k){
	if(k!=1){
		return jiecheng(k-1)*k;
	}else
		return 1;
}
void print(int *a, int length){
    for(int i=0; i<length; ++i){
		cout<<a[i];
	}
	cout<<endl;
}
void move(int* a, int length){
	bool tail0=false;;
	int tail0Num=0;
	int i=length-1; 
	if(a[i] == 0)
		tail0 = true;
	while( a[i] == 0 ){
		tail0Num++;
		i--;
	}

	while( a[i]== 1){
		i--; 
	}
	if(tail0== true){
		int beg=i+2;
		int end=length-1;
		for( int i=0; i<tail0Num; ++i){
			if(beg != end ){
				swap(a[beg],a[end]);
			}
			beg++;
			end--;
		}
	}
}

int main()
{
	int t;
	cin>>t;
	for( int i=0; i<t; ++i){
		int n ,m , k;
		cin>>n>>m>>k;
		if( (jiecheng(n+m)/ jiecheng(m)) /jiecheng(n)<k ){
			cout<<"Impossible"<<endl;
		}else{
			int* a = new int[n+m];
			for(int i=0; i<n; ++i){
				a[i]= 0 ;
			}
			for(int i=n; i<m+n; ++i){
				a[i]= 1 ;
			}
			print(a,n+m);
			for( int i=0; i<k-1; ++i){
				move(a,n+m);
				print(a,n+m);
			}
			print(a,n+m);
		}
	}
	return 0; 
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章