标签:
并查集可实现集合的快速合并与查找操作。路径压缩后的并查集可将每次合并或者查找的操作复杂度降低到O(1).
我的代码:
1 #include <iostream> 2 #include <string> 3 #include <map> 4 5 using namespace std; 6 7 #define MAXN 100005 8 9 map<string, int> mp; 10 11 struct unionFindSet 12 { 13 int st[MAXN]; 14 void init() 15 { 16 for(int i=0; i<MAXN; ++i) st[i] = i; 17 } 18 int findSet(int x) 19 { 20 if(x==st[x]) return x; 21 return st[x] = findSet(st[x]); //路径压缩 22 } 23 void unionSet(int x, int y) 24 { 25 int sx = findSet(x), sy = findSet(y); 26 st[sx] = sy; 27 } 28 }ufs; 29 30 int main() 31 { 32 int cnt, n; 33 bool op; 34 string name1, name2; 35 while(cin>>n) 36 { 37 mp.clear(); 38 cnt = 0; 39 ufs.init(); 40 while(n--) 41 { 42 cin>>op>>name1>>name2; 43 if(mp.find(name1)==mp.end()) mp[name1] = cnt++; 44 if(mp.find(name2)==mp.end()) mp[name2] = cnt++; 45 if(op) 46 { 47 int s1 = ufs.findSet(mp[name1]), s2 = ufs.findSet(mp[name2]); 48 cout<<(s1==s2?"yes":"no")<<endl; 49 } 50 else 51 { 52 ufs.unionSet(mp[name1], mp[name2]); 53 } 54 } 55 } 56 return 0; 57 }
题目链接:http://hihocoder.com/problemset/problem/1066
标签:
原文地址:http://www.cnblogs.com/pczhou/p/4296624.html