hdu 3172 Virtual Friends (字符串的并查集)

一开始一直wa,因为第一个数字t也是多组输入。

然后一直超时,因为我用的是C++里面的cin,所以非常耗时,几乎比scanf慢了10倍,但是加上了一个语句后:

std::ios::sync_with_stdio(false);                //是用来禁用cin这个兼容性的特性,禁用后就相差无几了

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <vector>
 4 #include <map>
 5 #include <string>
 6 #include <algorithm>
 7 using namespace std;
 8 map<string, string>fa;
 9 map<string, int>Rank;
10 const int maxn = 100005;
11 string a[maxn];
12 string b[maxn];
13 
14 string Find(string x){
15     if (x == fa[x])
16         return x;
17     else
18         return fa[x] = Find(fa[x]);
19 }
20 
21 void set_union(string x, string y){
22     string xx = Find(x);
23     string yy = Find(y);
24     //cout << "fa: " << xx << " " << yy << endl;
25     if (xx == yy){
26         cout << Rank[xx] << endl;
27     }
28     else{
29         fa[yy] = xx;
30         Rank[xx] += Rank[yy];
31         cout << Rank[xx] << endl;
32     }
33     /*
34     if (Rank[xx] > Rank[yy]){
35         fa[yy] = xx;
36         Rank[xx] += Rank[yy];
37         cout << Rank[xx] << endl;
38     }
39     else if (Rank[xx]==Rank[yy]){
40         fa[yy] = xx;
41         Rank[xx]+=Rank[yy];
42         cout << Rank[xx] << endl;
43     }
44     else{
45         fa[yy] = xx;
46         Rank[yy] += Rank[xx];
47         cout << Rank[yy] << endl;
48     }
49     */
50 }
51 
52 void init(int sum){
53     for (int i = 0; i < sum; i++){
54         fa[a[i]] = a[i];
55         fa[b[i]] = b[i];
56         Rank[a[i]] = Rank[b[i]] = 1;
57     }
58 }
59 
60 int main(){
61     std::ios::sync_with_stdio(false);
62     int t;
63     while (cin>>t){
64         while (t--){
65             int n;
66             cin >> n;
67             for (int i = 0; i < n; i++){
68                 cin >> a[i];
69                 cin >> b[i];
70             }
71             init(n);
72             for (int i = 0; i < n; i++){
73                 //cout << "#" << i << endl;
74                 //cout << a[i] << " " << b[i] << endl;
75                 set_union(a[i], b[i]);
76             }
77         }
78     }
79     //system("pause");
80     return 0;
81 }

 

posted @ 2017-11-18 19:20  ouyang_wsgwz  阅读(189)  评论(0编辑  收藏  举报