codeforces 766D Mahmoud and a Dictionary

题意:

给你n个词,m个关于这些词的关系(1表示同义2表示反义)如果给出的关系与前面的关系不冲突则输出YES反之则输出NO,再给出q组词,问这两个词的关系

 

题解:

带权并查集

w[i]表示与父节点的关系,0为同义,1为反义


#include<iostream>
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include<stdlib.h>
#include <string.h>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<time.h>
using namespace std;
#define MAX_N 100005
#define inf 0x7fffffff
#define LL long long
#define ull unsigned long long
#define mod 1000000007
LL INF=9e18;

int n,m,q;
int par[MAX_N];
int w[MAX_N];
map<string,int>mp;
void init()
{
    for(int i=0;i<=n;i++)
        par[i] = i;
}
int find(int x)
{
    if(x != par[x]) {
        int fx = find(par[x]);
        w[x] = (w[x] + w[par[x]]) % 2;
        par[x] = fx;
        return fx;
    }
    return x;
}
int main()
{
    cin >> n >> m >> q;
    for(int i=0;i<n;i++) {
        string str;
        cin >> str;
        mp[str] = i;
    }
    init();
    for(int i=0;i<m;i++) {
        int k;
        string s1,s2;
        cin >> k >> s1 >> s2;
        int x = mp[s1];
        int y = mp[s2];
        int fx = find(x);
        int fy = find(y);
        if(fx != fy) {
            par[fx] = fy;
            w[fx] = (w[x] + w[y] + k-1) % 2;
            cout << "YES" << endl;
        }
        else {
            if((w[x]+w[y])%2 != k-1)
                cout << "NO" << endl;
            else
                cout << "YES" << endl;
        }
    }
    for(int i=0;i<q;i++) {
        string s1,s2;
        cin >> s1 >> s2;
        int x = mp[s1];
        int y = mp[s2];
        int fx = find(x);
        int fy = find(y);
        if(fx == fy) {
            cout << (w[x] + w[y])%2 + 1 << endl;
        }
        else {
            cout << 3 << endl;
        }
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值