思路:
1.一开始我是想着把所有的结果全部存下来,然后就tle了(n的n次)
->改为把从给出的顺序开始全存下来,依旧不行
->最后改成如果遇到题目给出的顺序做个标记,然后开始cnt
(如果数据小一点,或许是可行的
2.然后需要解决的就是怎么判断是否一致的问题
用same[]数组判断当前位是否一致
用same1[]数组记录到1-n位是否都一致
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int n,m,cnt,num,vis[11111];
long long b[11111],ans[11111];
bool same[11111],same1[11111],flag;
void dfs(int depth)
{
if(depth==n+1)
{
if(cnt==0)
{
if (same1[n]) cnt++;
return;
}
if(cnt==m)
{
for(int i=1;i<=n;i++) cout<<ans[i]<<" ";
cout<<endl;
flag=true;//the answer has been calculated, no need to continue
return;
}
cnt++;
return;
}
for(int i=1;i<=n;i++)
{
if (vis[i]==0)
{
if (i==b[depth]) same[depth]=true;
else same[depth]=false;
same1[depth]=same1[depth-1]&same[depth];
if(cnt==0&&same1[depth]==0) continue ;
ans[depth]=i;
vis[i]=1;
dfs(depth+1);
vis[i]=0;
if (flag) return;
}
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>b[i];
cnt=0;
same1[0]=true;
dfs(1);
return 0;
}