1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| #include <cstdio> #include <algorithm> using namespace std; const int N = 1e5 + 10, M = 1e6 + 10; int n, m, ans, c[N], sz[M], p[M]; int idx, hd[M], nxt[N], edg[N]; void merge(int &x, int &y) { if (x == y) return; if (sz[x] > sz[y]) swap(x, y); for (int i = hd[x]; ~i; i = nxt[i]) ans -= (c[edg[i] - 1] == y) + (c[edg[i] + 1] == y); for (int i = hd[x]; ~i; i = nxt[i]) { c[edg[i]] = y; if (nxt[i] == -1) { nxt[i] = hd[y]; hd[y] = hd[x]; break; } } hd[x] = -1; sz[y] += sz[x]; sz[x] = 0; } void add(int a, int b) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i < M; i++) hd[i] = -1; for (int i = 1; i <= n; i++) { scanf("%d", &c[i]); if (c[i] != c[i - 1]) ans++; add(c[i], i); sz[c[i]]++; } for (int i = 0; i < M; i++) p[i] = i; for (int op; m; m--) { scanf("%d", &op); if (op == 1) { int x, y; scanf("%d%d", &x, &y); merge(p[x], p[y]); } else if (op == 2) printf("%d\n", ans); } return 0; }
|