0pts求条
查看原帖
0pts求条
1000414
Linhibit楼主2025/7/23 01:27

绝如望\

#include <iostream>
#include <algorithm>
#include <vector>
#define N 1000005
using namespace std;

int n, m, ans;
int a[N], sz[N], g[N];
vector<int> pos[N];
void merge(int x, int y)
{
    for (int i : pos[x]) 
    {
        if (i > 1) ans -= (a[i-1] != a[i]);
        if (i < n) ans -= (a[i] != a[i+1]);
    }
    for (int i : pos[x]) 
    {
        a[i] = y;
        pos[y].push_back(i);
    }
    for (int i : pos[x]) 
    {
        if (i > 1) ans += (a[i-1] != a[i]);
        if (i < n) ans += (a[i] != a[i+1]);
    }
    sz[y] += sz[x];
    sz[x] = 0;
    g[x] = y;
    pos[x].clear();
}

int main() 
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    cin >> n >> m;
    for (int i = 1; i <= n; i++) 
    {
        cin >> a[i];
        int c = a[i];
        if (!g[c]) g[c] = c; 
        pos[c].push_back(i);
        sz[c]++;
    }
    ans = 0;
    for (int i = 1; i < n; ++i) 
    {
        if (a[i] != a[i+1]) ans++;
    }
    ans++;

    while (m--) 
		{
        int op;
        cin >> op;
        if (op == 2) 
        {
            cout << ans << '\n';
        } 
        else 
        {
            int x, y;
            cin >> x >> y;
            if (x == y) continue;
            int rx = g[x], ry = g[y];
            if (rx == ry) continue;
            if (sz[rx] > sz[ry]) swap(rx, ry);
            merge(rx, ry);
        }
    }

    return 0;
}
2025/7/23 01:27
加载中...