Question source http://ac.jobdu.com/problem.php? PID = 1, 1526
Topic 1526: circle of friends
Time limit:1 second
Memory limit:128 MB
Special Judgment:No
Submit:411
Solution:100
-
Description:
-
If we know that there are n people and m friends (stored in the number R ). If two people are friends directly or indirectly (friends of friends ...), they think they belong to the same circle of friends. Please write a program to find out the total number of circle of friends among the N people.
Assume that n = 5, M = 3, r = {1, 2}, {2, 3}, {4, 5} indicates that there are 5 people, 1 and 2 are friends, 2 and 3 are friends, 4 and 5 are friends, then 1, 2, 3 belong to one circle of friends, 4, 5 belong to another circle of friends, the result is two moments.
-
Input:
-
The input contains multiple test cases. The first line of each test case contains two positive integers n, m, 1 = <n, m <= 100000. Next, there are m rows. Enter the numbers F and t (1 = <F, T <= N) of two people in each row, indicating that F and t are friends. When N is 0, the input ends and the case is not processed.
-
Output:
-
For each test case, the total number of friends in the N persons is displayed.
-
Sample input:
-
5 31 22 34 53 31 21 32 30
-
Sample output:
-
21
-
Source:
-
Xiaomi 2013 campus recruitment pen questions
Train of Thought: query the set path compression algorithm
import java.io.*;import java.util.*;public class Main {public static int n,m;public static int pattern[];public static void main(String[] args) {Scanner sc=new Scanner(new BufferedInputStream(System.in));PrintWriter pw=new PrintWriter(new BufferedOutputStream(System.out),true);while(sc.hasNext()){n=sc.nextInt();m=sc.nextInt();pattern=new int[n+1];for(int i=1;i<=n;i++){pattern[i]=i;}for(int i=0;i<m;i++){int a=sc.nextInt();int b=sc.nextInt();union(a,b);}int ans=0;for(int i=1;i<=n;i++){if(pattern[i]==i)ans++;}pw.println(ans);}}public static void union(int a,int b){int aa=fun(a);int bb=fun(b);if(aa==bb)return;if(aa>bb)pattern[bb]=aa;elsepattern[aa]=bb;}public static int fun(int aa){int p=pattern[aa];if(p==aa)return p;else return fun(p);}}