Topic links
Test instructions: N number (i.e. 1-n) and M operations:
1 means merging x and Y, 2 means moving x to the y set, and 3 for counting the number of elements in the X collection
1,3 say, the key is 2 operation, you can remove 2, delete the operation can find an additional number to replace X, so that there is a new collection, moved to the Y set to merge
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring>using namespace std;const int N = 100000;typedef Long long ll;int father[n + n + 10];int sum[n + n + 10],cnt[n + n + 10]; Sum of all elements within the collection and, CNT represents the number of int value[n + N + 10]; Represents the first I numeric int n,m,k;void init () {k = n + 1; for (int i = 0; I <= N; i++) {father[i] = i; Sum[i] = i; Cnt[i] = 1; Value[i] = i; }}int Find (int x) {if (x = = Father[x]) return x; return father[x] = Find (Father[x]);} void Union (int x, int y) {int fx = Find (x); int fy = Find (y); if (FX! = FY) {father[fx] = FY; Sum[fy] + = Sum[fx]; Cnt[fy] + = Cnt[fx]; }}void Remove (int x) {/* int fx = Find (value[x]); cnt[fx]--; SUM[FX]-= x; Value[x] = k; int fy = Find (value[y]); Father[k] = FY; cnt[fy]++; SUM[FY] + = x; k++; */INT FX = Find (value[x]); cnt[fx]--; Remove X from the parent node collection minus one sum[fx]-= x; Subtract x value[x from sum] = k; Using k instead of X, a separate set is generated, and the parent node is k cnt[k] = 1; SUM[K] = x; Father[k] = k; k++;} int main () {while (scanf ("%d%d", &n, &m)! = EOF) {k = n + 1; for (int i = 0; I <= N; i++) {father[i] = i; Sum[i] = i; Cnt[i] = 1; Value[i] = i; } int order,p,q; while (m--) {scanf ("%d", &order); if (order = = 1) {scanf ("%d%d", &p, &q); Union (Value[p], value[q]); } else if (order = = 2) {scanf ("%d%d", &p, &q); int FX = Find (value[p]); int fy = Find (value[q]); if (FX! = FY)//if p and Q are originally in a collection, then no operation is necessary. But the less this on WA, do not understand why the operation is not {Remove (P); Union (Value[p], value[q]); }} else if (order = = 3) {scanf ("%d", &P); int FX = Find (value[p]); printf ("%d%d\n", Cnt[fx], sum[fx]); }}} return 0;}
Uva11987almost Union-find (and set delete node)