Title Description:
If there is a known n person and M-to-friend relationship (stored in the number R). If two people are direct or indirect friends (friends of Friend's friends ...) ), think that they belong to the same circle of friends, please write a program to find out how many of these n people have a circle of friends.
if: n = 5, M = 3, R = {2, 3}, {4, 5}, 5 people, 1 and 2 are friends, 2 and 3 are friends, 4 and 5 are friends, 1, 2, 3 belong to a circle of friends, 4, 5 belong to another circle of friends, the result is 2 circle of friends.
Input:
The input contains multiple test cases, and the first line of each test case contains two positive integers n, m,1=<n,m<=100000. Next there are m lines, each line is entered with a number of two peoplef,t(1=<f,t<=n), indicating that F and T are friends. When n is 0 o'clock, the input ends and the use case is not processed.
Output:
For each test case, output how many circle of friends there are in this N person.
Sample input:
5 3
0 S
2 3
4 5
3 3
0 S
1 3
2 3
0
Sample output:
2
1
Thinking of solving problems
Use a forest of trees to solve problems, and each tree represents a circle of friends. Building two array IDs and Sz,id[x] represents the root node of x, Sz[x] represents the number of nodes in the tree with x as the root node.
- Initialize: For i = 1 to Personcount, id[i] = i, sz[i] = 1;
- Determine the input of a set of relationships, see whether the two nodes are located in the same tree (root node is the same), if different, the smaller tree is merged into a larger tree (the root node of the decimal root node is set to the root node of the tree), while the number of nodes of the tree is set to the tree node and small tree nodes.
(For a lookup function, to speed up the query, the path can be compressed, and the parent node of the node will be set to its grandfather nodes)
More detailed ideas: http://blog.csdn.net/dm_vincent/article/details/7655764
Implementation code
#include <iostream>using namespace STD;classuf{ Public: UF (intN) {id =New int[n]; SZ =New int[n]; Count = N-1; for(inti =0; I < n; i++) {Id[i] = i; Sz[i] =1; } }intGetCount () {returnCount }intFindset (intN) { while(n! = Id[n]) {Id[n] = id[id[n]]; n = id[n]; }returnN }voidUnionset (intXintY) {intDX = Findset (x);intdy = Findset (y);if(dx! = dy) {count--;if(SZ[DX] > Sz[dy]) {Id[dy] = dx; SZ[DX] + = Sz[dy]; }Else{ID[DX] = dy; Sz[dy] + = SZ[DX]; }}} ~uf () {Delete[] ID;Delete[] sz; }Private:int*id;int*sz;intCount;};intMain () {intPersoncount; while(Cin>>personcount, Personcount) {UF *uf =NewUF (Personcount +1);intRelationcount;Cin>>relationCount;intx, y; for(inti =0; i < Relationcount; i++) {Cin>>x>>y; Uf->unionset (x, y); }cout<<uf->getcount () <<endl;Deleteuf }return 0;}
and check set