hiho第十四周

並查集
基本思路,給每個人名編號(存到一個大的數組中,貌似也可用數據結構實現,稍後補),然後維護並查集

代碼如下:

#include <bits/stdc++.h>
#define maxn 200010
using namespace std;
int p[maxn];
int findpa( int x){
    return p[x] == x ? x : p[x] = findpa( p[x]);
}
void unionpa( int x, int y){
    int fx = findpa( x), fy = findpa( y);
    if ( fx != fy)  p[fy] = fx;
}
char a[20], b[20], str[maxn][20];
int main()
{
    int n, t, c = 0;


    scanf( "%d", &n);
    for ( int i = 0; i <= n * 2; i++){
        p[i] = i;
    }
    while ( n--){
        scanf( "%d%s%s", &t, a, b);
        int x = -1, y = -1;
        for ( int i = 0; i < c; i++){
            if ( !strcmp( a, str[i]))
                x = i;
            if ( !strcmp( b, str[i]))
                y = i;
        }
        if ( x == -1){
            x = c;
            strcpy( str[c], a);
            c++;
        }
        if ( y == -1){
            y = c;
            strcpy( str[c], b);
            c++;
        }
        if ( t){
            if ( findpa( x) == findpa( y))
                printf( "yes\n");
            else
                printf( "no\n");
        }
        else
            unionpa( x, y);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章