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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值