Http://poj.org/problem? Id = 2524 Like hdu-1213, there are n people first, then M relationships, ask how many people belong to different relationships.
<Span style = "font-size: 12px;"> # include <cstdio> int ID [50001], SZ [50001], n, m; int find (int p) {While (P! = ID [p]) {// path compression destroys the size information of the parent node of the current node, the parent node of the current node has changed ID [p] = ID [ID [p]; P = ID [p];} return P;} void UN (int p, int q) {int I = find (p); Int J = find (Q); if (I = J) return; if (SZ [I] <SZ [J]) {ID [I] = J; SZ [J] + = SZ [I];} // merge else {ID [J] = I; SZ [I] + = SZ [J];} n --; // after each merge, number of trees minus 1} int main () {// freopen ("a.txt", "r", stdin); int A, B, I, j = 1; while (scanf ("% d", & N, & M )! = EOF & N + M) {for (I = 1; I <= N; I ++) {ID [I] = I; SZ [I] = 1 ;} for (I = 1; I <= m; I ++) {scanf ("% d", & A, & B); UN (a, B );} printf ("case % d: % d \ n", J ++, n) ;}return 0 ;}</span>
Poj 2524 ubiquitous religions