UVA-10129 Play on Words

题目链接: Play on Words

题目大意: a单词的末尾字母若与b单词的首字母相同,则b可接在a的后面。给出一组单词,问是否可以连成且仅连成一条线。

解题思路: 把每个单词看作一条边,则此题就变成了求图中是否存在欧拉道路的问题,由于数据量小,把每个单词都DFS一遍,找到欧拉道路输出就行了。然而一开始在建图的时候用邻接表没能解决重边的问题,最后用“朴素”的邻接矩阵就Ok了。


代码如下:

#include <map>
#include <queue>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int inf = 0x3f3f3f3f;
const int maxn = 1e5 + 15;

int V, E, t, cnt;
int vis[200][200], temp[200][200];
int G[200][200];

int Euler(int u){
    for(int v = 'a'; v <= 'z'; v++){
        if(G[u][v] && temp[u][v]){
            temp[u][v]--;
            Euler(v);
            cnt++;
        }
    }
}

int main(){
    ios::sync_with_stdio(false);
    string s;
    cin >> t;
    while(t--){
        cin >> E;
        memset(vis, 0, sizeof vis);
        for(int i = 1; i <= E; i++){
            cin >> s;
            G[s[0]][s.back()]++;
            vis[s[0]][s.back()]++;
        }
        for(int i = 'a'; i <= 'z'; i++){
            cnt = 0;
            memcpy(temp, vis, sizeof vis);
            Euler(i);
            if(cnt == E) break;
        }
        if(cnt == E) cout << "Ordering is possible." << endl;
        else cout << "The door cannot be opened." << endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章