微軟2014機試第二題

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


看到這道題,我的第一思路就是排列組合,比如輸入n=2 ,m=3 ,那就是有2個0和3個1  , 再對這5個數進行排列,用遞歸的思想。

第一位排0,則再對剩下的n-1和m排列

第一位排1,則再對剩下的n和m-1排列

利用這種思想也很容易得出總共的排列次數


我的代碼如下

#include<stdio.h>
#include<stdlib.h>

int total(int n,int m)    //用來計算n和0和m個1排列的總個數 
{
	if(n==0 || m==0)
		return 1;
	else
		return (total(n-1,m)+total(n,m-1));
}

void findthekth(int pailie[] ,int n,int m,int len ,int k,int index,int *count)
{
	int i;
		
	if(  index >= len )
	{
		(*count)=(*count)+1;
		if((*count) == k)
		{
			for(i=0;i<len;i++)
			{
				printf("%d",pailie[i]);
			}
			printf("\n");
		}
		return ;
	}
	if(n>0)    //0的個數比0大 
	{		
     	pailie[index] = 0;
 		findthekth(pailie,n-1,m,len,k,index+1,count);//剩下n-1個0和m個1去排 
	}
    if(m>0)    //1的個數比0大 
	{
        pailie[index] = 1;
        findthekth(pailie,n,m-1,len,k,index+1,count);//剩下n個0和m-1個1去排	
	}	
}

int main()
{
	int num;
	int n ,m ,k,count ;
	scanf("%d",&num);
	
	int i,j;	
	int * pailie = (int *)malloc((n+m)*sizeof(int));
	for(i=0;i<num;i++)
	{
		j=0;
		count = 0;
		scanf("%d",&n);
		scanf("%d",&m);
		scanf("%d",&k);
		
       	if(k<=total(n,m))
	       	findthekth(pailie,n,m,n+m,k,0,&count);
       	else
       		printf("Impossible\n");
	}
	free(pailie);
}



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