您的位置:首页 > 其它

codeforces 766D Mahmoud and a Dictionary

2017-02-09 01:01 288 查看
题意:

给你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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: