connect components in undirected graph
Description
输入一个简单无向图,求出图中连通块的数目。
Input
输入的第一行包含两个整数n和m,n是图的顶点数,m是边数。1<=n<=1000,0<=m<=10000。
以下m行,每行是一个数对v y,表示存在边(v,y)。顶点编号从1开始。
Output
单独一行输出连通块的数目。
Sample Input
5 3 1 2 1 3 2 4
Sample Output
2
View Code
1 #include <iostream> 2 using namespace std; 3 4 #define max 1001 5 6 int rank[max]; 7 int father[max]; 8 9 void ini(int n) 10 { 11 for (int i = 1; i <= n; i++){ 12 father[i] = i; 13 rank[i] = 1; 14 } 15 } 16 17 int find(int x) 18 { 19 if (father[x] != x) 20 father[x] = find(father[x]); 21 return father[x]; 22 } 23 24 void Union(int x, int y) 25 { 26 int fatherX = find(x); 27 int fatherY = find(y); 28 if (fatherX == fatherY) 29 return; 30 if (rank[fatherX] >= rank[fatherY]){ 31 father[fatherX] = fatherY; 32 rank[fatherX] += rank[fatherY]; 33 } 34 else{ 35 father[fatherY] = fatherX; 36 rank[fatherY] += rank[fatherX]; 37 } 38 } 39 40 int main() 41 { 42 int n, m, a, b; 43 cin >> n >> m; 44 ini(n); 45 for (int i = 0; i < m; i++){ 46 cin >> a >> b; 47 Union(a, b); 48 } 49 int count = 0; 50 for (int i = 1; i <= n; i++){ 51 if (father[i] == i){ 52 count++; 53 //cout << i << " + " << endl; 54 } 55 } 56 cout << count << endl; 57 58 // system("PAUSE"); 59 return 0; 60 }


浙公网安备 33010602011771号