K-th string (微软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 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

开始想着找找规律,发现可以用排列组合的方法来求 N,M 时的个数,因而根据个数来求不同K时的输出。

后来做着做着就乱掉了。冷静下来分析了下发现

Num(N, M) = Num(N - 1, M) + Num(N, M - 1)

这就可以作为递推公式了,因此可以做出一个关于N\M的matrix[N][M]矩阵。

再根据 K 的值参考矩阵选择输出 0 或者 1 .


贴代码:

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

//Matrix[I][J]代表I个零以及J个一能够组成的不同排列的个数
//递推关系:matrix[N][M] = matrix[N-1][M] + matrix[N][M-1];
int matrix[30][30];


//将递归计算的到的matrix的值存入matrix矩阵,以减少运算。
int SetNumMatrix(int N, int M)
{
	if(N == 0 || M == 0){
		matrix[N][M] = 1;
	}
	else if(matrix[N][M] == 0){
		int Val1 = matrix[N - 1][M] == 0 ? SetNumMatrix(N - 1, M) : matrix[N - 1][M];
		int Val2 = matrix[N][M - 1] == 0 ? SetNumMatrix(N, M - 1) : matrix[N][M - 1];
		matrix[N][M] = Val1 + Val2;
	}
	return matrix[N][M];
}


//递归打印符合要求的字符序列。
void printfRecursive(int N, int M, int K)
{
	if(N == 0)
		for(int i = 0; i < M; i++) putchar('1');
	else if(M == 0)
		for(int i = 0; i < N; i++) putchar('0');
	
	else if(K <= matrix[N-1][M]){
		putchar('0');
		printfRecursive(N-1, M, K);
	}
	else{
		putchar('1');
		printfRecursive(N, M-1, K - matrix[N-1][M]);
	}
}


//matrix[N][M] = matrix[N-1][M] + matrix[N][M-1];
void printK(int N, int M, int K)
{
	if(K > matrix[N][M])
		printf("Impossible");
	else
		printfRecursive(N,M,K);
	putchar('\n');
}


int main()
{
	int n;
	int N, M, K;

	//初始化Matrix数组用于查询。
	SetNumMatrix(15, 15);

	int maxNum, tmp;
	scanf("%d", &n);
	for(int i = 0; i < n; i++){
		scanf("%d %d %d", &N, &M, &K);
		printK(N, M, K);
	}
	return 0;
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值