题意:给出n个单词,m条关系,q个询问,每个对应关系有,a和b是同义词,a和b是反义词,如果对应关系无法成立就输出no,并且忽视这个关系,如果可以成立则加入这个约束,并且输出yes。每次询问两个单词的关系,1,同义词,2,反义词,3,不确定
题解:这题思路比较奇特,开辟2*n的并查集的空间,第i+n代表i的反义词所在的树,初始为i+n,也就是说i+n代表i的反义词
#include<bits/stdc++.h> using namespace std; #define ll long long const int maxn=1e5+10; char a[30],b[30]; map<string,int>ma; int book[maxn*2]; int fin(int x) { if(book[x]==x)return x; else return book[x]=fin(book[x]); } int main() { int n,m,q; scanf("%d %d %d",&n,&m,&q); for(int i=1;i<=n;i++) { scanf("%s",a); ma[a]=i; } for(int i=1;i<=2*n;i++) book[i]=i; for(int i=1;i<=m;i++) { int com; scanf("%d %s %s",&com,a,b); int x=ma[a],y=ma[b]; if(com==1) { if(fin(x)==fin(y+n)||fin(y)==fin(x+n)) printf("NO\n"); else { printf("YES\n"); book[fin(x)]=fin(y); book[fin(x+n)]=fin(y+n); } } else { if(fin(x)==fin(y)||fin(x+n)==fin(y+n)) printf("NO\n"); else { printf("YES\n"); book[fin(x)]=fin(y+n); book[fin(y)]=fin(x+n); } } } for(int i=1;i<=q;i++) { scanf("%s %s",a,b); int x=ma[a],y=ma[b]; if(fin(x)==fin(y)||fin(x+n)==fin(y+n)) printf("1\n"); else if(fin(x)==fin(y+n)||fin(y)==fin(x+n)) printf("2\n"); else printf("3\n"); } return 0; }
原文地址:https://www.cnblogs.com/carcar/p/10126848.html
时间: 2024-10-14 04:38:11