poj1386 Play on Words

題面在這裏

題意:

給n個字符串,兩個字符串若頭尾字符相同可以連接起來,問你是否可以把n個字符串連接起來。

做法:

對於一個單詞,把它頭尾的字符之間連一條有向邊,然後問題轉化爲求這個圖是否存在歐拉路徑。
一個有向圖存在歐拉路徑的判斷方式:

  1. 圖弱連通
  2. 所有點的入度都等於出度;或只有兩個點的入度不等於出度,且這兩個點一個入度-出度=1,另一個出度-入度=1.

代碼:

/*************************************************************
    Problem: poj 1386 Play on Words
    User: bestFy
    Language: C++
    Result: Accepted
    Time: 329MS
    Memory: 660K
    Submit_Time: 2018-01-24 11:19:16
*************************************************************/

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cctype>
#include<cstdlib>
#include<cmath>
using namespace std;
typedef long long ll;

inline ll read() {
    char ch = getchar(); ll x = 0; int op = 1;
    for(; !isdigit(ch); ch = getchar()) if(ch == '-') op = -1;
    for(; isdigit(ch); ch = getchar()) x = x*10+ch-'0';
    return x*op;
}
inline void write(ll a) {
    if(a < 0) putchar('-'), a = -a;
    if(a >= 10) write(a/10); putchar('0'+a%10);
}

int n;
char s[1010];
int fa[100], in[100], out[100];

inline int getfa(int x) { return fa[x] == x ? x : fa[x] = getfa(fa[x]); }
int main() {
    int test = read();
    while(test --) {
        n = read(); int st = 0;
        memset(in, 0, sizeof in); memset(out, 0, sizeof out);
        for(int i = 1; i <= 26; i ++) fa[i] = i;
        for(int i = 1; i <= n; i ++) {
            scanf("%s", s); int len = strlen(s);
            int x = s[0]-'a'+1, y = s[len-1]-'a'+1, fx, fy;
            in[y] ++; out[x] ++; st = x;
            fx = getfa(x); fy = getfa(y);
            if(fx != fy) fa[fx] = fy;
        } bool flag = 1; int t1 = 0, t2 = 0;
        for(int i = 1; i <= 26; i ++) {
            if(in[i]+out[i] == 0) continue;
            if(getfa(st) != getfa(i) || abs(in[i]-out[i]) > 1) { flag = 0; break; }
            if(abs(in[i]-out[i]) == 1) if(in[i]-out[i] == 1) t1 ++; else t2 ++;
        }
        if(flag && (t1 == 0 && t2 == 0 || t1 == 1 && t2 == 1)) puts("Ordering is possible.");
        else puts("The door cannot be opened.");
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章