树状数组求调
查看原帖
树状数组求调
707461
100kt_WNW楼主2022/5/4 19:35
 * @Author: 100kt_northwest
 * @Date: 2022-05-04 17:27:25
 * @LastEditors: 100kt_northwest
 * @LastEditTime: 2022-05-04 19:33:40
 */
#include <cstdio>
#include <iostream>
#include <memory.h>
#define N 20000009
using namespace std;
int n;
int s[N], cnt[N];
inline int LSB(int x) { return x & -x; }
void add(int x, int v)
{
    cnt[x] += v;
    while (x < N)
        s[x] += v, x += LSB(x);
}
int myrank(int x)
{
    int res = 1;
    --x;
    while (x)
        res += s[x], x -= LSB(x);
    return res;
}
int KthNum(int k)
{
    int ans = 0, ct = 0;
    for (int i = 26; i >= 0; --i) {
        ans += (1 << i);
        if (ans >= N || ct + s[ans] >= k)
            ans -= (1 << i);
        else
            ct += s[ans];
    }
    ++ans;
    return ans;
}
int pre(int x)
{
    return KthNum(myrank(x) - 1);
}
int nxt(int x)
{
    return KthNum(myrank(x) + (cnt[x] > 0));
}
void quick()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
}
signed main()
{
    quick();
    cin >> n;
    while (n--) {
        int op, k;
        cin >> op >> k;
        switch (op) {
        case 1:
            add(k + 10000001, 1);
            break;

        case 2:
            add(k + 10000001, -1);
            break;
        case 3:
            cout << myrank(k + 10000001) << endl;
            break;
        case 4:
            cout << KthNum(k) - 10000001 << endl;
            break;
        case 5:
            cout << pre(k + 10000001) - 10000001 << endl;
            break;
        case 6:
            cout << nxt(k + 10000001) - 10000001 << endl;
            break;
        }
    }
    return 0;
}
2022/5/4 19:35
加载中...