Codeforces 501D Misha and Permutations Summation

康托展开后的两个序列相加后 Mod(n!) 即为一个新的康托展开的序列,不过每一位都要考虑是否要进。

因为n过大,所以用树状数组进行康托展开。

而逆康托展开时,可以用二分查询,m-sum(m)是非降序列。


代码:

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 2e5+5;
int n, a[MAXN], c[MAXN];

int lowbit(int x) {
    return x&-x;
}

void add(int x, int t) {
    while(x <= n) {
        c[x] += t;
        x += lowbit(x);
    }
}

int sum(int x) {
    int ret = 0;
    while(x > 0) {
        ret += c[x];
        x -= lowbit(x);
    }
    return ret;
}

int main() {
    cin >> n;
    memset(c, 0, sizeof(c));
    for(int i = n-1; i >= 0; i--) {
        int t; scanf("%d", &t);
        t++;
        add(t, 1);
        a[i] = t-sum(t);
    }

    memset(c, 0, sizeof(c));

    for(int i = n-1; i >= 0; i--) {
        int t; scanf("%d", &t);
        t++;
        add(t, 1);
        a[i] += t-sum(t);
    }

    for(int i = 0; i < n; i++) {
        a[i+1] += a[i]/(i+1);
        a[i] %= i+1;
    }

    memset(c, 0, sizeof(c));

    a[n-1]++;
    add(a[n-1], 1);
    for(int i = n-2; i >= 0; i--) {
        int l = 1, r = n;
        while(l < r) {
            int m = (l+r)>>1, t = m-sum(m)-1;
            if(t < a[i]) l = m+1;
            else r = m;
        }
        a[i] = l;
        add(l, 1);
    }

    for(int i = n-1; i >= 0; i--) printf("%d ", a[i]-1);
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值