启发式合并求助
查看原帖
启发式合并求助
984679
illidan_楼主2024/7/20 12:19
#include <bits/stdc++.h>
//#define int long long
#define ull unsigned long long
#define id(i, j) (i - 1) * m + j
#define endl '\n'

using namespace std;

const int N = 2e6 + 5;
const int Mx = 0x3f3f3f3f3f3f3f3f;
typedef pair<int, int> PII;

int n, m, ans, T;
int a[N], st[N], ed[N], ne[N], sz[N], d[N];

void hb(int x, int y)
{
    for (int j = ed[x]; j; j = ne[j])
    {
        if (y == a[j - 1])
            ans--;
        if (y == a[j + 1])
            ans--;
    }
    for (int j = ed[x]; j; j = ne[j])
        a[j] = y;
    ne[st[x]] = ed[y], ne[y] = ne[x], sz[y] += sz[x];
    st[x] = 0;
    sz[x] = 0;
    ed[x] = 0;
}

signed main()
{
    //ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        cin >> a[i];
        d[a[i]] = a[i];
        if (a[i] != a[i - 1])
            ans++;
        if (ed[a[i]] == 0)
            st[a[i]] = i;
        ne[i] = ed[a[i]];
        ed[a[i]] = i;
        sz[a[i]]++;
    }
    for (int i = 1; i <= m; i++)
    {
        int op;
        cin >> op;
        if (op == 2)
            cout << ans << endl;
        else
        {
            int x, y;
            cin >> x >> y;
            if (d[x] == d[y])
                continue;
            if (sz[d[x]] > sz[d[y]])
                swap(d[x], d[y]);
            if (sz[d[x]] == 0)
                continue;
            hb(d[x], d[y]);
        }
    }
    return 0;
}

找了很长时间也没找到哪错了

2024/7/20 12:19
加载中...