HDU 3172 Virtual Friends (并查集)

Virtual Friends

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2964 Accepted Submission(s): 861


Problem Description
These days, you can do all sorts of things online. For example, you can use various websites to make virtual friends. For some people, growing their social network (their friends, their friends' friends, their friends' friends' friends, and so on), has become an addictive hobby. Just as some people collect stamps, other people collect virtual friends.

Your task is to observe the interactions on such a website and keep track of the size of each person's network.

Assume that every friendship is mutual. If Fred is Barney's friend, then Barney is also Fred's friend.
 
Input
Input file contains multiple test cases.
The first line of each case indicates the number of test friendship nest.
each friendship nest begins with a line containing an integer F, the number of friendships formed in this frindship nest, which is no more than 100 000. Each of the following F lines contains the names of two people who have just become friends, separated by a space. A name is a string of 1 to 20 letters (uppercase or lowercase).
 
Output
Whenever a friendship is formed, print a line containing one integer, the number of people in the social network of the two people who have just become friends.
 
Sample Input
1 3 Fred Barney Barney Betty Betty Wilma
 
Sample Output
2 3 4
 


题意:问你就是到每句话的这两个人的朋友网里面有多少人

思路: 并查集

import java.util.*;
import java.io.*;

public class Main {
	int M = 100000;
	int n, m;
	HashMap<String, Integer> hm = new HashMap<String, Integer>();//用来给字符串编号
	int patten[] = new int[M + 1];
	int ans[] = new int[M + 1];

	public static void main(String[] args) {
		new Main().work();
	}

	void work() {
		Scanner sc = new Scanner(new BufferedInputStream(System.in));
		while (sc.hasNext()) {
			hm.clear();
			n = sc.nextInt();
			for (int j = 0; j < n; j++) {
				//并查集初始化
				for (int i = 1; i <=M; i++) {
					patten[i] = i;
				}
				Arrays.fill(ans, 1);
				m = sc.nextInt();
				int count = 1;
				for (int i = 0; i < m; i++) {
					String s1 = sc.next();
					String s2 = sc.next();
					if (!hm.containsKey(s1)) {
						hm.put(s1, count);
						count++;
					}
					if (!hm.containsKey(s2)) {
						hm.put(s2, count);
						count++;
					}
					union(hm.get(s1), hm.get(s2));

				}
			}
		}
	}
	//并查集合并
	void union(int a, int b) {

		int pa = find(a);
		int pb = find(b);
		if (pa == pb) {
			System.out.println(ans[pa]);
			return;
		}
		if(pa>pb){
			patten[pb]=pa;
			ans[pa]+=ans[pb];
			System.out.println(ans[pa]);
		}
		else{
			patten[pa]=pb;
			ans[pb]+=ans[pa];
			System.out.println(ans[pb]);
		}
	}
	//并查集查找
	int find(int x) {
		if(patten[x]==x)
			return x;
		int t=patten[x];
		patten[x]=find(t);//路径优化
		return patten[x];
	}
}



原文地址:https://www.cnblogs.com/bbsno1/p/3266628.html