我是靠谱客的博主 机智背包,这篇文章主要介绍Codeforces 396 div.2 带权并查集,现在分享给大家,希望可以做个参考。

题意:
一共给你N个单词,其中有M个关系是已知的,我们要对Q对单词进行关系查询。
其中M个关系,要么两个单词是同义词,要么两个单词是反义词。
对于查询,如果两个单词是同义词,输出1,如果是反义词输出2,如果不能确定输出3.
分析:
带权并查集。权值的设置需要考虑

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> #include <string> #include <map> using namespace std; typedef long long ll; const int N=1e5+5; int fa[N],ran[N]; int _find(int x) { if(fa[x]!=x) { int pre=fa[x]; fa[x]=_find(fa[x]); ran[x]=(ran[x]+ran[pre])%2; //a->fa>ffa //ran[a]是a和fa的关系,ran[pre]是fa和ffa的关系,新的ran[a]是a和ffa的关系,根据关系向量得该表达式 } return fa[x]; } int main() { int n,m,q,r; char sr[25],ssr[25]; scanf("%d%d%d",&n,&m,&q); map<string,int> mp; for(int i=1;i<=n;i++) { scanf("%s",sr); mp[sr]=i; fa[i]=i,ran[i]=0; } for(int i=0;i<m;i++) { scanf("%d%s%s",&r,sr,ssr); int a=mp[sr],b=mp[ssr]; int aa=_find(a),bb=_find(b); if(aa!=bb) { puts("YES"); fa[bb]=aa; ran[bb]=(ran[a]-ran[b]+r+1)%2; } else { n=(ran[a]-ran[b]+2)%2; n==r-1?puts("YES"):puts("NO"); } } while(q--) { scanf("%s%s",sr,ssr); int a=mp[sr],b=mp[ssr]; int aa=_find(a),bb=_find(b); if(aa!=bb)puts("3"); else { n=(ran[a]-ran[b]+2)%2; printf("%dn",n+1); } } }

最后

以上就是机智背包最近收集整理的关于Codeforces 396 div.2 带权并查集的全部内容,更多相关Codeforces内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(92)

评论列表共有 0 条评论

立即
投稿
返回
顶部