codeforces 766 D. Mahmoud and a Dictionary(种类并查集+stl)

题目链接:http://codeforces.com/contest/766/problem/D

题意:给你n个单词,m个关系(两个单词是反义词还是同义词),然后问你所给的关系里面有没有错的,最后再给你q个询问,问你两个单词之间的关系是什么,

同义词输出1,反义词输出2,不确定输出3;

其实就是种类并查集。种类并查集怎么做之前的随笔中有说过。

 

#include <iostream>
#include <cstring>
#include <map>
using namespace std;
const int M = 1e5 + 10;
int f[M] , root[M] , n , m;
void init() {
    for(int i = 1 ; i <= n ; i++) {
        f[i] = i , root[i] = 0;
    }
}
int find(int x) {
    if(x == f[x])
        return x;
    int tmp = find(f[x]);
    root[x] = (root[x] + root[f[x]]) % 2;
    return f[x] = tmp;
}
string s , s1 , s2;
map<string , int>mmp;
int main() {
    int x , y , num , q;
    cin >> n >> m >> q;
    init();
    for(int i = 0 ; i < n ; i++) {
        cin >> s;
        mmp[s] = i + 1;
    }
    for(int i = 1 ; i <= m ; i++) {
        cin >> num >> s1 >> s2;
        x = mmp[s1] , y = mmp[s2];
        int t1 = find(x) , t2 = find(y);
        if(num == 1) {
            if(t1 == t2) {
                if(root[x] != root[y]) {
                    cout << "NO" << endl;
                }
                else {
                    cout << "YES" << endl;
                }
            }
            else {
                cout << "YES" << endl;
                f[t1] = t2;
                root[t1] = root[y] - root[x];
                root[t1] = (root[t1] + 2) % 2;
            }
        }
        else {
            if(t1 == t2) {
                if(root[x] == root[y]) {
                    cout << "NO" << endl;
                }
                else {
                    cout << "YES" << endl;
                }
            }
            else {
                cout << "YES" << endl;
                f[t1] = t2;
                root[t1] = (root[y] + 1 - root[x]);
                root[t1] = (root[t1] + 2) % 2;
            }
        }
    }
    while(q--) {
        cin >> s1 >> s2;
        x = mmp[s1] , y = mmp[s2];
        int t1 = find(x) , t2 = find(y);
        if(t1 == t2) {
            if(root[x] == root[y]) {
                cout << 1 << endl;
            }
            else {
                cout << 2 << endl;
            }
        }
        else {
            cout << 3 << endl;
        }
    }
    return 0;
}

转载于:https://www.cnblogs.com/TnT2333333/p/6690348.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值