1. 程式人生 > >codeforces#766 D. Mahmoud and a Dictionary (並查集)

codeforces#766 D. Mahmoud and a Dictionary (並查集)

namespace define scanf 對應關系 force sha ict codeforce sharp

題意:給出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;
}

  

codeforces#766 D. Mahmoud and a Dictionary (並查集)