首页 > 其他 > 详细

UVA - 10129 Play on Words(欧拉回路)

时间:2017-01-12 12:24:02      阅读:282      评论:0      收藏:0      [点我收藏+]

题意:将n个单词排成一个序列,保证相邻单词相邻处字母相同。

分析:每个单词看做一条有向边,字母为点,并查集看图是否连通,因为是有向图,所以最多只能有两个点入度不等于出度,且这两个点一个入度比出度大1,一个出度比入度大1

并查集,单词的首字母是尾字母的祖先。

#pragma comment(linker, "/STACK:102400000, 102400000")
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define Min(a, b) ((a < b) ? a : b)
#define Max(a, b) ((a < b) ? b : a)
typedef long long ll;
typedef unsigned long long llu;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
const ll LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const double eps = 1e-8;
const int MAXN = 1000 + 10;
const int MAXT = 10000 + 10;
using namespace std;
char s[MAXN];
int fa[30];
int in[30];
int out[30];
int Find(int x){
    return fa[x] = (x == fa[x]) ? x : Find(fa[x]);
}
int main(){
    int T;
    scanf("%d", &T);
    while(T--){
        for(int i = 0; i <= 25; ++i){
            fa[i] = i;
        }
        memset(in, 0, sizeof in);
        memset(out, 0, sizeof out);
        int n;
        scanf("%d", &n);
        for(int i = 0; i < n; ++i){
            scanf("%s", s);
            int len = strlen(s);
            int x = s[0] - a;
            int y = s[len - 1] - a;
            ++in[y];
            ++out[x];
            int tx = Find(x);
            int ty = Find(y);
            fa[ty] = tx;//首字母是尾字母的祖先
        }
        bool ok = true;
        int cnt = 0;
        for(int i = 0; i < 26; ++i){//统计连通块个数
            if((in[i] || out[i]) && fa[i] == i){
                ++cnt;
            }
        }
        if(cnt > 1) ok = false;//图不连通
        int num1 = 0;//入度比出度大1的结点数
        int num2 = 0;//出度比入度大1的结点数
        for(int i = 0; i < 26; ++i){
            if(!ok) break;
            if(in[i] != out[i]){
                if(in[i] - out[i] == 1) ++num1;
                else if(out[i] - in[i] == 1) ++num2;
                else{
                    ok = false;
                    break;
                }
            }
        }
        if(ok){
            if(!((num1 == 0 && num2 == 0) || (num1 == 1 && num2 == 1))) ok = false;
        }
        if(!ok){
            printf("The door cannot be opened.\n");
        }
        else{
            printf("Ordering is possible.\n");
        }
    }
    return 0;
}

 

UVA - 10129 Play on Words(欧拉回路)

原文:http://www.cnblogs.com/tyty-Somnuspoppy/p/6275639.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!