hdu 1116 Play on Words(歐拉圖+並查集)

小記:歐拉圖的判定還是蠻有用的


思路:因爲要將所有的字符串合併,你頭等於我尾的字符,這樣這兩個字符串才能連起來。而要所有的都連起來,那麼這圖就要是歐拉圖。

我們可以用並查集判定字符連串是否只有一個,多餘一個就不是歐拉圖。必然不會有解。

而只有一個,那麼就用歐拉圖的判定來解決問題即可。


代碼:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <map>
#include <set>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <string>

using namespace std;

#define mst(a,b) memset(a,b,sizeof(a))
#define REP(a,b,c) for(int a = b; a < c; ++a)
#define eps 10e-8

const int MAX_ = 110;
const int N = 100010;
const int INF = 0x7fffffff;

int in[MAX_], out[MAX_], ans[MAX_];

int n,m,cnt;
int fa[MAX_];
char str[MAX_*10];

int findfa(int x)
{
    if(fa[x] == x)return x;
    return fa[x] = findfa(fa[x]);
}


int main() {
    int T, s, t, tmp, temp;
    string s1, s2;
    
    bool flag;
    scanf("%d", &T);

    while(T-- && scanf("%d", &n)) {
        mst(out, 0);
        mst(in, 0);

        REP(i, 1, 27){
            fa[i] = i;
        }

        flag = 0;
        tmp = 0;

        REP(i, 1, n+1) {
            scanf("%s", str);
            s = str[0] - 'a' + 1;
            t = strlen(str);
            t = str[t-1] - 'a' + 1;
            if(findfa(s) != findfa(t))fa[t] = s;
            in[t] ++;
            out[s] ++;
        }

        REP(i, 1, 27){
            if(fa[i] == i && (in[i] || out[i]))++tmp;
        }
        if(tmp > 1){
            printf("The door cannot be opened.\n");
            continue;
        }

        s = 0; t= 0; temp = 0;
        REP(i, 1, 27){
            if(in[i] - out[i] == 1)++s;
            else if(out[i] - in[i] == 1)++t;
            else if(in[i] != out[i]) ++temp;
        }

        if((s == 1 && t == 1 && temp == 0) ||(!s&&!t&&!temp)){
            printf("Ordering is possible.\n");
        }
        else
            printf("The door cannot be opened.\n");


    }
    return 0;
}


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