1. 程式人生 > >hdu 3172 Virtual Friends (字符串的並查集)

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

for sys ons str += turn pre tdi 特性

一開始一直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 }

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