If there is a known n person and M-to-friend relationship (stored in array R). If two people are direct or indirect friends (friends of Friend's friends ...) ), they are considered to belong to the same circle of friends. Please write a program to find out how many friends there are in this N person.
For example: n=5,m=3,r={{1,2},{2,3},{4,5}, which indicates that there are 5 people, 1 and 2 are friends, 2 and 3 are friends, 4 and 5 are friends, 1, 2, 3 belong to the same circle of friends, 4, 5 belong to another circle of friends. The result is a circle of 2 friends.
This problem can be achieved through a collection of data structures.
- At the beginning, each element is a collection, and then the two collections are merged by law.
The code is as follows:
UnionFindSet.h:
#pragma onceclass unionfindset{public:unionfindset (int N): _a (new Int[n]), _n (N) {memset (_a,-1, N * 4);//Set the initial element value of each set to-1} Find the root of the element int FindRoot (int x) {while (_a[x] >= 0) {x = _a[x];} return x;} Merge void Union (int x1, int x2) {int root1 = FindRoot (x1); int root2 = FindRoot (x2); _a[root1] + = _a[root2];//merges the root of element 2 into the root of element 1 _ A[root2] = root1;//The value of element 2 is set to the total number of elements 1}//merged after the aggregate int count () {int count = 0;for (size_t i = 0; i < _n; ++i) {if (_a[i] < 0) {++c Ount;}} return count;} protected:int* _a;//Element set size_t _n;//elements};
Test.cpp
#include <iostream>using namespace std; #include "UnionFindSet.h" int groupsoffriends (int n, int m, int r[][2]) { Unionfindset UFs (n+1); for (size_t i = 0; i < m; ++i) {int x1 = r[i][0];int x2 = r[i][1];ufs. Union (x1, x2);} Return UFS. The Count () -1;//element collection starts at 0 and should be subtracted from the 0 collection}void Test () {int r[][2] = {{{}, {1,3}, {4,5}};int count = Groupsoffriends (5, 3, R);cout< <count<<endl;} int main () {Test (); return 0;}
650) this.width=650; "Src=" Http://s2.51cto.com/wyfs02/M01/84/23/wKiom1eGehTi63rGAABspscuWiE821.png-wh_500x0-wm_3 -wmp_4-s_779105942.png "title=" 20160714012715.png "alt=" Wkiom1egehti63rgaabspscuwie821.png-wh_50 "/>
Process:
650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/84/23/wKiom1eGdxvRTPJmAAA9hISb0Zo997.png "title=" 20160714011359.png "alt=" Wkiom1egdxvrtpjmaaa9hisb0zo997.png "/>
This article is from the "zgw285763054" blog, make sure to keep this source http://zgw285763054.blog.51cto.com/11591804/1826229
C + + implementation and check set