Problem F
Permutation
Input: Standard Input
Output: StandardOutput
Given N and K find the N’thpermutation of the integers from 1 to K when those permutations arelexicographically ordered. N startsfrom 0. Since N is very large N will be represented by a sequence of Knon-negative integers S1, S2 ,…, Sk. From thissequence of integers N can be calculated with the following expression.
Input
First line of the input containsT(≤10) the number of test cases. Each of these test cases consists of 2lines. First line contains a integer K(1≤K≤50000). Next linecontains K integers S1, S2 ,…, Sk.(0≤Si≤K-i).
Output
For each test case output contains N’th permutation ofthe integers from 1 to K. These K integers should be separated by a singlespace.
SampleInput Output for Sample Input
4 3 2 1 0 3 1 0 0 4 2 1 1 0 4 1 2 1 0
| 3 2 1 2 1 3 3 2 4 1 2 4 3 1
|
康托展开:点击打开链接
才发现原来写的八数码建立的表就是康托展开。。
简单的说就是每位找出1-K中之前没出现的数并且比这位数小的有多少个,这个个数乘以排列在这个数后面的数的个数的阶乘。康托展开的数就是排列在全排列中的位置,和原来的排列是一一对映的关系。
题目已经给了s1...sn,每次只要找1-K中之前没出现的第si小的数(从0开始),就知道第i位是什么了。如果每位都循环找一遍时间太长,用线段树维护当前区间没有出现的数的个数。如果左边剩下的个数不够si,就往右边找si-左边剩下的个数。
#include<cstring>
#include<cstdio>
#include<iostream>
#include<climits>
#include<cmath>
#include<algorithm>
#include<queue>
#define INF 0x3f3f3f3f
#define MAXN 50010
#define MAXNODE 4*MAXN
using namespace std;
int T,K,cnt[MAXNODE];
void build(int o,int L,int R){
cnt[o]=R-L+1;
if(L==R) return;
int lc=(o<<1),rc=(o<<1|1),mid=(L+R)/2;
build(lc,L,mid);
build(rc,mid+1,R);
}
int query(int o,int L,int R,int s){
cnt[o]--;
if(L==R) return L;
int lc=(o<<1),rc=(o<<1|1),mid=(L+R)/2;
if(cnt[lc]>s) return query(lc,L,mid,s); //注意编号从0开始,所以左边剩余的个数要大于s
else return query(rc,mid+1,R,s-cnt[lc]);
}
int main(){
freopen("in.txt","r",stdin);
scanf("%d",&T);
while(T--){
scanf("%d",&K);
build(1,1,K);
for(int i=0;i<K;i++){
int s;
scanf("%d",&s);
if(i) printf(" ");
printf("%d",query(1,1,K,s));
}
puts("");
}
return 0;
}