您的位置:首页 > 其它

微软2014实习生招聘笔试第2题 the k-th string

2014-04-12 21:16 489 查看
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

求全排列的问题.

使用STL #include<algorithm> ,可能超时

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

// 计算组合数
long long com(int n,int r)
{
if(n-r < r) r= n-r;  //减少计算量
int i,j,s=1;
for(i=0,j=1;i<r;++i)

{
s*=(n-i);
for(;j<=r && s%j==0; ++j) s/=j;  // 防止溢出
}
return s;
}

int main()
{
string str;
int T,a,b,i,j;
long long m,Count;
cin>>T;
while(T--)
{
Count=0;
str.clear();
cin>>a>>b>>m;
for(i=0;i<a;i++)
str+="0";
for(j=0;j<b;j++)
str+="1";
if(m>com(a+b,b))
cout<<"Impossible"<<endl;
else
{
while (next_permutation(str.begin(), str.end()))
{
++Count;
if(Count+1==m)
{
cout<<str<<endl;
break;
}
}

}
}
return 0;
}


方法二: 回溯法

#include <stdio.h>
#define MAX_N 33

int n,m=2;
long long Count=0,times; // 共有n个数,其中互不相同的有m个
int rcd[MAX_N];   //记录每个位置填的数字
int used[MAX_N]; //标记m个数可以使用的次数
int num[MAX_N]; // 存放互不相同的m个数 0,1

long long com(int n, int r)
{
if(n-r < r) r= n-r;   // 减少计算量
int i,j,s=1;
for(i=0,j=1;i<r;++i)

{
s*=(n-i);
for(;j<=r && s%j==0; ++j) s/=j;  // 尽量避免越界
}
return s;
}

void unrepeat_permutation(int l)
{
int i;
if(l==n)
{
Count++;
if(Count==times)   //查找到所需的数字
{
for(i=0;i<n;i++)
{
printf("%d",rcd[i]);
if(i<n-1) printf(" ");
}
printf("\n");

}
return;
}
for(i=0;i<m;i++) //回溯求解
{
if(used[i]>0)
{
used[i]--;
rcd[l] = num[i];
unrepeat_permutation(l+1);
used[i]++;
}
}
}

int main()
{
int a,b,i,T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d%lld",&a,&b,×);
n=a+b;
if(times>com(n,a))  // 判断是否超出组合范围
{
printf("Impossible\n");
continue;
}
used[0]=a;  used[1]=b;  //记录0,1的个数
num[0]=0;   num[1]=1;   //记录可能出现的数字
Count=0;
unrepeat_permutation(0);
}
return 0;
}


第一题scanf,gets 浪费了太多时间!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: