Description
求一个0~N-1的排列(即每个数只能出现一次),给出限制条件(一张N*N的表,第i行第j列的1或0,表示为j-1这个数不能出现在i-1这个数后面,并保证第i行第i列为0),将这个排列看成一个自然数,求从小到大排序第K个排列。
Input
输入描述:
N<=10,K<=500000
输入样例:
3 2
0 1 1
1 0 0
0 1 0
Output
输出描述:
第一行为N和K,接下来的N行,每行N个数,0表示不能,1表示能
输出样例:
1 0 2
源码
#include <stdio.h>
#include <string.h>
int limit[15][15]; //限制条件
int number[15],occupy[15];
int N,K,cnt=0;
int judge(int pos,int n) //判断j这个数能不能出现在i的后面
{
if(pos==0) return 1;
if(!limit[number[pos-1]][n])
return 0;
return 1;
}
void calAllSort(int depth)
{
if(depth>=N) return;
for(int i=0;i<N;i++)
{
if(cnt==K) return;
if(occupy[i]==0&&judge(depth,i))
{
number[depth]=i;
if(depth==N-1)
{
cnt++;
if(cnt==K)
{
for(int i=0;i<N;i++)
printf("%d ",number[i]);
return;
}
}
occupy[i]=1;
calAllSort(depth+1);
occupy[i]=0;
}
}
}
int main()
{
//freopen("input/sortproblem.txt","r",stdin);
memset(occupy,0,sizeof(occupy));
scanf("%d%d",&N,&K);
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
scanf("%d",&limit[i][j]);
}
}
calAllSort(0);
return 0;
}