Permutation (树状数组)

Given N and K find the N-th permutation of the integers from 1 to K when those permutations are
lexicographically ordered. N starts from 0. Since N is very large N will be represented by a sequence
of K non-negative integers S1, S2, . . . , Sk. From this sequence of integers N can be calculated with
the following expression.

Input
First line of the input contains T (≤ 10) the number of test cases. Each of these test cases consists of
2 lines. First line contains a integer K (1 ≤ K ≤ 50000). Next line contains K integers S1, S2, . . . , Sk.
(0 ≤ Si ≤ K − i).
Output
For each test case output contains N-th permutation of the integers from 1 to K. These K integers
should be separated by a single space.
Sample Input
4
3
2 1 0
3
1 0 0
4
2 1 1 0
4
1 2 1 0
Sample Output
3 2 1
2 1 3
3 2 4 1
2 4 3 1

题目大概:
有t组样例,每组样例有个数k,接下来k个数,分别试s1,s2...sk。
最终是求出k个数的第N个全排列是什么,N 用题目给出的公式算出。
思路:
由于题目要求全排列是按字典序大小来的,那么如果一个数列1  2  3  4.
当i=1时,s1=1时,符合条件的全排列,一定时 2 . . . 到2 . . .的某个数,一定是2开头。
因为(k-i)是剩下的i个数的全排列,第si,就是本位应该是第si+1大的数开头。
所以,最终只需要一位一位求出第i位的数就可以了,第i位的数是剩下的数中的第si+1大的数。
代码:

#include 

using namespace std;
const int maxn=5e4+10;
int c[maxn];
int k;
int a[maxn];
int lowbit(int x)
{
    return x&(-x);
}
void add(int x,int v)
{
    while(x0)
    {
        sum+=c[x];
        x-=lowbit(x);
    }
    return sum;
}
int work(int d)
{
    int l=1,r=k;
    while(l<=r)
    {
        int mid=(l+r)/2;
        if(sum(mid)



你可能感兴趣的:(树状数组)