Circle of Friends (25 points)
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.
Finally, analyze the time and space complexity of the code you write. The rating will refer to the correctness and efficiency of the code.
C + +:
int friends (int n, int m, int* r[]);
Java:
int friends (int n, int m, int[][] r);
The Circle of Friends is a question of investigation and collection
The implementation method n marks the set of the element with the smallest number, and n defines an array SET[1..N], where Set[i] represents the set where element I resides;
| 1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
| 1 |
2 |
1 |
4 |
2 |
6 |
1 |
6 |
2 |
2 |
Disjoint collection: {1,3,7}, {4}, {2,5,9,10}, {6,8} implementation code FIND1 (x) {return set[x];} time complexity O (1); Merge1 (A, b) {i = min (a, b); j = Max (A, b); for (k=1; k<=n; k++) {if (set[k] = = j) Set[k] = i; The time Complexity O (N) specific code is as follows:
1#include <iostream>;2 using namespacestd;3 4 int Set[ -];5 6 intFindintx) {7 intR=x;8 while(Set[r]!=R) {9R=Set[R];Ten returnR; One } A } - - voidMergeintAintb) { the intC=find (a); - intD=find (b); - if(c<d) - Set[d]=C; + Else - Set[c]=D; + A } at - intFriendsintNintMint*r[]) { - intCount=0; - for(intI=0; i<n;i++){ - Set[i]=i; - } incout<<Set[0]<<Set[1]<<Set[2]<<Set[3]<<Set[4]<<Set[5]<<Endl; - for(intI=0; i<m;i++){ toMerge ((r[i][0]), (r[i][1])); + } - for(intj=1; j<=n;j++){ the if(Set[j]==j) *count++; $ }Panax Notoginsengcout<<Set[0]<<Set[1]<<Set[2]<<Set[3]<<Set[4]<<Set[5]<<Endl; -cout<<count<<Endl; the returncount; + A } the intMain () { + inta[][3]={{1,2},{2,3},{4,5}}; - int*input[]={&a[0][0],&a[1][0],&a[2][0]}; $Friends6,3, input); $}