题目链接
 大意:给你两个数n,k,让你求出n的所有全排列中差异序列字典序第k小的排列
 差异序列为     pi=ai+1−ai,i∈[1,n)
 思路:直接dfs枚举差异序列从小往大搜,然后对不合法的情况去掉(差异序列中元素的最大-最小<n-1才合法,重复的也不合法)
 细节见代码:
#include<bits/stdc++.h>
#define LL long long
#define fi first
#define se second
#define mp make_pair
#define pb push_back
using namespace std;
LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
LL lcm(LL a,LL b){return a/gcd(a,b)*b;}
LL powmod(LL a,LL b,LL MOD){LL ans=1;while(b){if(b%2)ans=ans*a%MOD;a=a*a%MOD;b/=2;}return ans;}
const int N = 503;
int t,n,k;
int vis[N],p[N];
bool dfs(int now,int pre,int l,int r){
	if(now==n){
		if(k==1){
			for(int i=0;i<n;i++){
				cout<<p[i]-l+1;
				if(i<n-1)cout<<' ';
				else cout<<'\n';
			}
			return 1;
		}
		k--;
		return 0;
	}
	for(int i=1-n;i<=n-1;i++){//枚举差异序列字典序最小
		if(!vis[i+pre]){
			vis[i+pre]=1;
			if(max(i+pre,r)-min(l,i+pre)<=n-1){
				p[now]=i+pre;
				if(dfs(now+1,i+pre,min(i+pre,l),max(i+pre,r))){
					vis[i+pre]=0;
					return 1;
				}
			}
			vis[i+pre]=0;
		}
	}
	return 0;
}
int main(){
	ios::sync_with_stdio(false);
	for(cin>>t;t;t--){
		cin>>n>>k;int sta=0;
		vis[n]=1;
		p[0]=n;
		dfs(1,n,n,n);//相对大小
		vis[n]=0;
	}	
	return 0;
}

 京公网安备 11010502036488号
京公网安备 11010502036488号