Untitled
unknown
c_cpp
3 years ago
1.4 kB
9
Indexable
#include <iostream> using namespace std; const int maxn = 105; int idx[maxn]; int size[maxn]; int find_root(int x) { while(idx[x] != x) { idx[x] = idx[idx[x]]; x = idx[x]; } return x; } bool check(int A, int B) { if(find_root(A) == find_root(B)) { return true; } return false; } void union_two_elements(int A, int B) { int root_a = find_root(A); int root_b = find_root(B); if(root_a != root_b) { if(size[root_a] < size[root_b]) { idx[root_a] = idx[root_b]; size[root_b] += size[root_a]; } else { idx[root_b] = idx[root_a]; size[root_a] += size[root_b]; } } } int main() { for(int i = 0; i < maxn; i++) { idx[i] = i; size[i] = 1; } while(true) { string s; cin >> s; if(s == "union") { int a,b; cin >> a >> b; union_two_elements(a, b); } else if(s == "check") { int a, b; cin >> a >> b; if(check(a, b)) { cout << "YES" << endl; } else { cout << "NO" << endl; } } else if(s == "size") { int a; cin >> a; cout << size[find_root(a)] << endl; } } return 0; }
Editor is loading...