[HNOI2009]梦幻布丁【线段树合并】

版权声明:https://blog.csdn.net/qq_41730082 https://blog.csdn.net/qq_41730082/article/details/88032970

题目链接


  一开始是在splay专题下找的这道题,但是一想,好像更贴近线段树的区间连续问题,然后就想着先去用线段树去写这道题,听闻会出现颜色会超出1e7的范畴,所以,我就不考虑用数组去开了,直接写了map<>的来解决这个问题。

  利用线段树合并,对于已有的每个颜色来看,我们可以去知道最开始的情况,可以直接求得,然后就是考虑每次的更新,将一个颜色变成另一个颜色的时候不要忘记去初始化这个颜色清空,不然,下次要是还改变这个颜色,岂不是在无中生有?(就是这个问题,一开始没注意到,WA了好几次……QAQ)


#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN = 1e6 + 7;
int N, Q, tot, ans;
struct node
{
    int lc, rc, val;
    bool l, r;
    node() { lc = rc = val = 0; l = r = false; }
}t[maxN<<1];
void pushup(int rt)
{
    t[rt].l = t[t[rt].lc].l;    t[rt].r = t[t[rt].rc].r;
    t[rt].val = t[t[rt].lc].val + t[t[rt].rc].val - (t[t[rt].lc].r && t[t[rt].rc].l);
}
void update(int &rt, int l, int r, int k)
{
    if(!rt) rt = ++tot;
    if(l == r) { t[rt].l = t[rt].r = true; t[rt].val = 1; return; }
    int mid = HalF;
    if(k <= mid) update(t[rt].lc, l, mid, k);
    else update(t[rt].rc, mid + 1, r, k);
    pushup(rt);
}
void Merge(int &p1, int &p2, int l, int r)
{
    if(l == r) return;
    int mid = HalF;
    if(t[p1].lc && t[p2].lc) Merge(t[p1].lc, t[p2].lc, l, mid);
    else if(t[p2].lc) t[p1].lc = t[p2].lc;
    if(t[p1].rc && t[p2].rc) Merge(t[p1].rc, t[p2].rc, mid + 1, r);
    else if(t[p2].rc) t[p1].rc = t[p2].rc;
    pushup(p1);
    p2 = 0;
}
map<int, int> root; //为了避免root的时候的颜色数量不确定,故利用map来写(离散作用)
int main()
{
    scanf("%d%d", &N, &Q);
    ans = tot = 0;
    int las = -INF;
    for(int i=1, color; i<=N; i++)
    {
        scanf("%d", &color);
        update(root[color], 1, N, i);
        if(las != color) ans++;
        las = color;
    }
    int op, now, to;
    while(Q--)
    {
        scanf("%d", &op);
        if(op == 1)
        {
            scanf("%d%d", &now, &to);
            if(now == to || !root[now]) continue;
            if(!root[to]) { root[to] = root[now]; root[now] = 0; continue; }
            ans -= t[root[now]].val + t[root[to]].val;
            Merge(root[to], root[now], 1, N);
            ans += t[root[to]].val;
        }
        else printf("%d\n", ans);
    }
    return 0;
}
/*
4 3
1 2 2 1
2
1 2 1
2
*/

/*
9 9
1 2 5 3 1 1 2 3 2
2
1 2 1
2
1 1 3
2
1 1 3
2
1 5 3
2
ans:
8
6
3
3
1
*/

猜你喜欢

转载自blog.csdn.net/qq_41730082/article/details/88032970