深度搜索DFS
Permutation
Time Limit:1000ms Memory Limit:65535KB
Description
Selecting m of n integers to form permutations, in accordance with the order of increasing from left to right.
For example, m=3, n=5, the whole permutations are:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
the 3th permutation is 0 1 4
For example, m=3, n=5, the whole permutations are:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
the 3th permutation is 0 1 4
Input
Only one line with three integers: n, m, i
1<=n<=100, 1<=i<=10000
1
Output
One line contains the ith permutation
Sample Input
5 3 3
Sample Output
0 1 4
Hint
#include<iostream>
#include<cstring>
int m,n,ith,a[105],cc=0,find=0;
void dfs(int pre,int deep)
{//已有深度和层次
if(find)
return;
if(deep==m)
{
cc++;
if(cc==ith)
{
for(int j=0;j<m;j++)
printf("%d ",a[j]);
printf("\n");
find=1;
}
return;
}
for(int i=pre+1;i<n;i++)
{
a[deep]=i;
dfs(i,deep+1);
if(find)
return;
}
}
int main()
{
scanf("%d%d%d",&n,&m,&ith);
memset(a,0,sizeof(a));
dfs(-1,0);
return 0;
}
#include<cstring>
int m,n,ith,a[105],cc=0,find=0;
void dfs(int pre,int deep)
{//已有深度和层次
if(find)
return;
if(deep==m)
{
cc++;
if(cc==ith)
{
for(int j=0;j<m;j++)
printf("%d ",a[j]);
printf("\n");
find=1;
}
return;
}
for(int i=pre+1;i<n;i++)
{
a[deep]=i;
dfs(i,deep+1);
if(find)
return;
}
}
int main()
{
scanf("%d%d%d",&n,&m,&ith);
memset(a,0,sizeof(a));
dfs(-1,0);
return 0;
}