FZU 2155 allies and fzu2155 allies
Problem 2155 allies
Problem Description
There are N countries in the world. For simplicity, the number ranges from 0 ~ N-1, if a and B are allies, B and c are allies, then a and c are also allies. In addition, each country has the right to announce the Alliance's withdrawal (note that the alliance can be further formed after the Alliance ).
Define the following two operations:
"M x y": the alliance between X and Y
"S x": the country of X announces withdrawal from the Alliance
Input
Multiple cases.
In each case, enter N and M (1 ≤ N ≤ 100000, 1 ≤ M ≤ 1000000), N is the number of countries, and M is the number of operations.
Next, enter M rows.
End input when N = 0, M = 0
Output
The number of consortium outputs for each group of cases. The format is shown in the example.
Sample Input5 6 M 0 1 M 1 2 M 1 3 S 1 M 1 2 S 33 1 M 1 20 0 Sample OutputCase #1: 3 Case #2: 2
Code:
/*** Solution: Contains deleted and query set questions, and uses a real [] array to mark the real location of each vertex. * The purpose is to delete a vertex, move his position to the end of the original total number group, * so that the original array will not be damaged. */# Include <stdio. h> # include <string. h> # define MAX 500005int father [MAX]; int real [MAX]; int vis [MAX]; int n, m, all; int find (int x) {if (father [x] = x) return x; elsereturn (father [x] = find (father [x]);} void merge (int a, int B) {int x, y; x = find (a); y = find (B); if (x! = Y) father [x] = y;} int main () {int t = 1; while (scanf ("% d", & n, & m )! = EOF) {if (0 = n & 0 = m) return 0; char op; all = n; memset (vis, 0, sizeof (vis )); for (int I = 0; I <n; I ++) {father [I] = I; real [I] = I ;}for (int I = 0; I <m; I ++) {getchar (); scanf ("% c", & op); if ('M' = op) {int a, B; scanf ("% d", & a, & B); merge (real [a], real [B]); // connect the real location} else {int x; scanf ("% d", & x); father [all] = all; real [x] = all ++; // Delete the x point and place the actual position of x to the end of the original array .}} Int ans = 0; for (int I = 0; I <n; I ++) {int u = find (real [I]); if (0 = vis [u]) {vis [u] = 1; ans ++ ;}} printf ("Case # % d: % d \ n ", t ++, ans);} return 0 ;}