0
点赞
收藏
分享

微信扫一扫

HDOJ 1027 Ignatius and the Princess II (DFS、next_permutation函数)

独兜曲 2023-03-02 阅读 43


给你N个整数,分别是1,2,3,。。。N。问你全排列的第M个排列为多少?

InputThe input contains several test cases. Each test case consists of two numbers, N and M(1<=N<=1000, 1<=M<=10000). You may assume that there is always a sequence satisfied the BEelzebub's demand. The input is terminated by the end of file.


OutputFor each test case, you only have to output the sequence satisfied the BEelzebub's demand. When output a sequence, you should print a space between two numbers, but do not output any spaces after the last number.


Sample Input

6 4 11 8

Sample Output

1 2 3 5 6 4 1 2 3 4 5 6 7 9 8 11 10

next_permutation

#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
int n,m;
int a[10001];
while(scanf("%d%d",&n,&m)!=EOF)
{
int cnt=1;
memset(a,0,sizeof(a));
for(int i=0;i<n;i++)
{
a[i]=i+1;
}
do{
if(cnt++==m) break;
}while(next_permutation(a,a+n));
for(int i=0;i<n-1;i++)
{
printf("%d ",a[i]);
}printf("%d\n",a[n-1]);
}return 0;
}
//next_permutation是个好东西

DFS

#include<cstdio>  
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int num[1010],vis[1010];
int n,ans;
bool f;
void dfs(int x)
{
if(x==n+1)
{
if(ans>0) ans--;
else
{
f=true;
for(int i=1;i<n;i++)
printf("%d ",num[i]);
printf("%d\n",num[n]);
}
}
if(f) return ;
for(int i=1;i<=n;i++)
{
if(!vis[i])
{
vis[i]=1;
num[x]=i;
dfs(x+1);
vis[i]=0;
}
}
}
int main()
{
while(scanf("%d%d",&n,&ans)!=EOF)
{
ans--;
f=false;
memset(num,0,sizeof(num));
memset(vis,0,sizeof(vis));
dfs(1);
}
return 0;
} //方法是这样的 不过超时了




举报

相关推荐

0 条评论