【带权并查集】Mahmoud and a Dictionary

来源:互联网 发布:河南移动数据运营中心 编辑:程序博客网 时间:2024/05/21 09:29
#include <algorithm>#include <string>#include <map>#include <iostream>using namespace std;int *p, *g;int getset(int x){if (p[x] == x)return x;int y = getset(p[x]);g[x] = (g[p[x]] + g[x] + 2) % 2;return p[x] = y;}void merge(int z,int x, int y){z--;int xs = getset(x);int ys = getset(y);if (xs == ys){if ((g[x] - g[y] + 2) % 2 == z){cout << "YES" << endl;return;}else{cout << "NO" << endl;return;}}p[xs] = ys;g[xs] = (g[y] - g[x] + z + 2) % 2;cout << "YES" << endl;return;}int main(){int n, a, b;map<string, int> m;cin >> n >> a >> b;p = new int[n];g = new int[n];for (int i = 0; i < n; i++){p[i] = i;g[i] = 0;}for (int i = 0; i < n; i++){string tmp;cin >> tmp;m[tmp] = i;}string tmp1, tmp2;for (int i = 0; i < a; i++){int gx;cin >> gx >> tmp1 >> tmp2;merge(gx, m[tmp1], m[tmp2]);}for (int i = 0; i < b; i++){cin >> tmp1 >> tmp2;int x = getset(m[tmp1]);int y = getset(m[tmp2]);if (x == y)cout << (g[m[tmp1]] - g[m[tmp2]] + 2) % 2 + 1 << endl;else cout << 3 << endl;}//system("pause");return 0;}

阅读全文
0 0