2014微软在线测试-K-th string-未提交

题意

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
01010111011

思路:

先求出最小组合成的数,然后逐渐加1遍历,直到求出第k个符合0和1数目的数(也就是1的位数等于输入的M)。

所有组合种数是C(n+m)n,求出总数,如果k>总数,则返回impossible。

int转二进制字符串的函数:String s = Integer.toBinaryString(value);//首位是1,高位0省略

代码未提交测试,本地测试了样例数据能通过

import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		Main mainc= new Main();
		int N = in.nextInt();
		int[] zero = new int[N];
		int[] one = new int[N];
		int[] kth = new int[N];
		for(int i=0;i<N;i++){
			zero[i] = in.nextInt();
			one[i]=in.nextInt();
			kth[i]=in.nextInt();		
		}
		for(int i=0;i<N;i++){
			if(mainc.count(zero[i],one[i])<kth[i]){
				System.out.println("Impossible");
			}else{
				int min = mainc.min(one[i]);
				int j=1;
				while(j<=kth[i]){				
					min++;
					int onecount=mainc.countone(min);
					if(onecount == one[i]){
						j++;
					}
					if(j==kth[i]){
						System.out.println(mainc.conventToNBit(min, one[i]+zero[i]));
						break;
					}
				}
			}		
		}	
	}
	
	int count(int zero,int one){
		int all=zero+one;
		int allj =1;
		int onej =1;
		int zeroj =1;
		for(int i=all;i>0;i--){
			allj *= i;
		}
		for(int i=one;i>0;i--){
			onej *= i;
		}
		for(int i=zero;i>0;i--){
			zeroj *= i;
		}
		return allj/(zeroj*onej);
	}
	
	int min(int one){
		int min=0;
		for(int i=0;i<one;i++){
			min += Math.pow(2, i);
		}
		return min;
	}
	
	int countone(int value){
		String s = Integer.toBinaryString(value);
		int ret = 0;
		for(int i=0;i<s.length();i++){
			if(s.charAt(i)=='1'){
				ret++;
			}
		}
		return ret;
	}
	
	String conventToNBit(int i,int n){
		String s = Integer.toBinaryString(i);	
		if(s.length()==n){
			return s;
		}else{
			StringBuilder sd = new StringBuilder(s);
			int cha = n-s.length();
			for(int j=0;j<cha;j++){
				sd.insert(0, '0');
			}
			return sd.toString();
		}
	}
}



你可能感兴趣的:(2014微软在线测试-K-th string-未提交)