Source: HDU 2473 junk-Mail Filter
In step 2, operate m x, y, and merge X and Y into a set. S x, remove X from the set where it is located, and create itself into a set.
Ideas: it is not easy to delete a vertex. If 0 1 2 can define an array ing in a set, the actual vertex corresponding to each vertex starts with a [0] = 0 A [1] = 1. [2] = 2 it means you are all yourself
Now remove 2. You can define a new vertex. The original vertex to be deleted must be a [2] = 3. The current 3 is the original 2. The original set is degraded. A vertex is merged every time. processing Array
# Include <cstdio> # include <cstring> using namespace STD; const int maxn = 1100010; int f [maxn], a [maxn], flag [maxn]; int CNT; void Init (int n) {for (INT I = 1; I <= N; I ++) f [I] = A [I] = I; CNT = N; memset (flag, 0, sizeof (FLAG);} int find (int x) {If (X! = F [x]) return f [x] = find (F [x]); Return f [X];} void merge (int x, int y) {x = find (x); y = find (y); If (X! = Y) f [x] = y;} void del (int x) {find (A [x]); F [++ CNT] = CNT; A [x] = CNT;} int main () {int CAS = 1; int t; int n, m; while (scanf ("% d", & N, & M) & (N | M) {Init (n); While (M --) {char s [10]; scanf ("% s", S ); if (s [0] ='s ') {int X; scanf ("% d", & X); X ++; del (x );} else {int X, Y; scanf ("% d", & X, & Y); X ++, y ++; merge (A [X], A [y]) ;}} int ans = 0; For (INT I = 1; I <= N; I ++) {int x = find (A [I]); If (! Flag [x]) {ans ++; flag [x] = 1 ;}} printf ("case # % d: % d \ n", CAS ++, ans);} return 0 ;}