Algorithm
problem Link : https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=1549
There is a town with N citizens. It is known that some pairs of people are friends. According to the famous saying that “The friends of my friends are my friends, too” it follows that if A and B are friends and B and C are friends then A and C are friends, too. Your task is to count how many people there are in the largest group of friends. Input Input consists of several datasets. The first line of the input consists of a line with the number of test cases to follow. The first line of each dataset contains tho numbers N and M, where N is the number of town’s citizens (1 ≤ N ≤ 30000) and M is the number of pairs of people (0 ≤ M ≤ 500000), which are known to be friends. Each of the following M lines consists of two integers A and B (1 ≤ A ≤ N, 1 ≤ B ≤ N, A ΜΈ= B) which describe that A and B are friends. There could be repetitions among the given pairs. Output The output for each test case should contain (on a line by itself) one number denoting how many people there are in the largest group of friends on a line by itself.
Sample Input 2 3 2 1 2 2 3 10 12 1 2 3 1 3 4 5 4 3 5 4 6 5 2 2 1 7 1 1 2 9 10 8 9
Sample Output 3 7
Code Examples
#1 Code Example with C Programming
Code -
C Programming
#include <bits/stdc++.h>
using namespace std;
int groupSize[30000];
int highest;
int udfsFind(int* udfs, int n){
return udfs[n] == n ? n : udfsFind(udfs,udfs[n]);
}
void udfsJoin(int* udfs, int a, int b){
if(udfsFind(udfs,a) == udfsFind(udfs,b)) return;
int newSize = groupSize[udfsFind(udfs,a)] += groupSize[udfsFind(udfs,b)];
highest = max(newSize,highest);
udfs[udfsFind(udfs,b)] = udfsFind(udfs,a);
}
int main() {
int t,n,m,a,b;
cin >> t;
while(t--){
cin >> n >> m;
highest = 1;
int udfs[n];
for(int i=0;i i+It n;i++){
groupSize[i] = 1;
udfs[i] = i;
}
for(int i=0;i<m;i++){
cin >> a >> b;
udfsJoin(udfs,a-1,b-1>;
}
cout << highest << endl;
}
}
Copy The Code &
Try With Live Editor
Input
3 2
1 2
2 3
10 12
1 2
3 1
3 4
5 4
3 5
4 6
5 2
2 1
7 1
1 2
9 10
8 9
Output
7
Demonstration
UVA Online Judge solution - 10608-Friends - UVA Online Judge solution in C,C++,java