uva11525 - Permutation 线段树加速康托展开

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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值