标签:
并查集+路径压缩
数据量不大,没有加秩优化
代码:
1 #include <iostream> 2 #include <map> 3 #include <cstring> 4 5 using namespace std; 6 7 #define SIZE 100010 8 9 int disjoin[SIZE]; 10 map<string, int> a2i; 11 12 int find(int a) { 13 if (!disjoin[a] || disjoin[a] == a) 14 disjoin[a] = a; 15 else 16 disjoin[a] = find(disjoin[a]); 17 return disjoin[a]; 18 } 19 20 void merge(int a, int b) { 21 disjoin[find(a)] = find(b); 22 } 23 24 bool check(int a, int b) { 25 return find(a) == find(b); 26 } 27 28 int main() { 29 int N; 30 int op; 31 string a, b; 32 int ai, bi; 33 int num = 0; 34 35 memset(disjoin, 0, sizeof(int) * SIZE); 36 cin >> N; 37 while (N--) { 38 cin >> op >> a >> b; 39 ai = a2i[a]; 40 bi = a2i[b]; 41 if (!a2i[a]) 42 ai = a2i[a] = ++num; 43 if (!a2i[b]) 44 bi = a2i[b] = ++num; 45 46 if (op == 0) 47 merge(ai, bi); 48 else 49 cout << (check(ai, bi) ? "yes" : "no") << endl; 50 } 51 return 0; 52 }
标签:
原文地址:http://www.cnblogs.com/boring09/p/4377136.html