SPOJ DQUERY(主席树)

传送门

题意:
给长度为n的序列,询问区间中的元素个数(去重后的元素个数),m次询问, n [ 1 , 3 1 0 4 ] , m [ 1 , 2 1 0 5 ] n在[1,3*10^4], m在[1,2*10^5]

思路:
用主席树去写,每颗树存从 [ 1 , i ] [1,i] 区间的信息,我们把这颗树中出现多次的数去重,只保最每个数在最右边出现的位置信息,其余位置的sum为0,然后询问时候,在含有当前区间信息的树中,进行区间求和

参考代码:

#include <cstdio>
#include <algorithm>
#include <vector>
#include <iostream>
#include <map>
#include <queue>
#include <cstring>
#include <string>
#include <cstdlib>
#include <cmath>
#include <set>
using namespace std;
const int inf = (1 << 30);
typedef long long ll;
const int maxn = 1e5 + 5;
vector<int> vec;
struct node
{
    int ls, rs, sum;
} tr[maxn * 50];
int rt[maxn], cnt;
void inser(int ver, int &now, int L, int R, int pos, int w)
{
    now = ++cnt;
    tr[now] = tr[ver];
    tr[now].sum = tr[ver].sum + w;
    if (L == R)
        return;
    int mid = L + R >> 1;
    if (mid >= pos)
        inser(tr[ver].ls, tr[now].ls, L, mid, pos, w);
    else
        inser(tr[ver].rs, tr[now].rs, mid + 1, R, pos, w);
}
int ask(int now, int L, int R, int ql, int qr)
{
    if (L >= ql && R <= qr)
        return tr[now].sum;
    int mid = L + R >> 1;
    int ans = 0;
    if (ql <= mid)
        ans += ask(tr[now].ls, L, mid, ql, qr);
    if (qr > mid)
        ans += ask(tr[now].rs, mid + 1, R, ql, qr);
    return ans;
}
map<int, int> mp;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    mp.clear();
    int n, x;
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        cin >> x;
        if (!mp[x])
            inser(rt[i - 1], rt[i], 1, n, i, 1);
        else
            inser(rt[i - 1], rt[i], 1, n, mp[x], -1), inser(rt[i], rt[i], 1, n, i, 1);
        mp[x] = i;
    }
    int m;
    cin >> m;
    while (m--)
    {
        int ql, qr;
        cin >> ql >> qr;
        cout << ask(rt[qr], 1, n, ql, qr) << endl;
    }
}

猜你喜欢

转载自blog.csdn.net/yangzijiangac/article/details/105907343
今日推荐