hdu 3172 Virtual Friends 并查集的应用,输入有坑!!!!

Virtual FriendsTime Limit: 4000/2000 MS (Java/Others)Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 5717Accepted Submission(s): 1606

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

13Fred BarneyBarney BettyBetty Wilma

Sample Output

234

假设有t组测试数据应该这样写:

int t ;while(~scanf("%d",&t))//特别 需要注意

我的代码:

#include <iostream>#include <cstdio>#include <string>#include <set>#include <algorithm>const int MAX = 100100 ;using namespace std ;string name[MAX] ,line1[MAX],line2[MAX];int f[MAX] ,c[MAX];void init(int n){for(int i = 0 ; i < n + 10 ; ++i){f[i] = i ;c[i] = 1 ;}}int find(int x){int r = x ;while(r!=f[r]){r = f[r] ;}int temp ;while(x != f[x]){temp = f[x] ;f[x] = r ;x = temp ;}return r ;}void join(int x ,int y){int fx = find(x) , fy = find(y) ;if(fx != fy){f[fx] = fy ;c[fy] += c[fx] ;}}bool cmp(const string &a , const string &b){return a<b ;}int Bsearch(string &s , int len){int i = 0 , j = len-1 ;while(i<=j){int mid = (i+j)>>1 ; if(name[mid] > s){j = mid – 1 ;}else if(name[mid]<s){i = mid + 1 ;}else{return mid ;}}return i ;}int main(){int t ;while(~scanf("%d",&t))//特别 需要注意 {while(t–){set<string>s;int n ;scanf("%d",&n);for(int i = 0 ; i < n ; ++i){cin>>line1[i]>>line2[i] ;s.insert(line1[i]);s.insert(line2[i]) ;}set<string>::iterator it = s.begin() ;int len = 0 ;for( ; it != s.end() ; ++it){name[len++] = *it ;}sort(name,name+len,cmp) ;init(len) ;for(int i = 0 ; i < n ; ++i){int x = Bsearch(line1[i],len) ;int y = Bsearch(line2[i],len) ;join(x,y) ;printf("%d\n",c[find(y)]) ;}}}return 0 ;}与君共勉

,选择逃避,选择被动的去面对生活。

hdu 3172 Virtual Friends 并查集的应用,输入有坑!!!!

相关文章:

你感兴趣的文章:

标签云: