HDU 1116 Play on Words



http://acm.hdu.edu.cn/showproblem.php?pid=1116

有向图寻找欧拉路径

1.连通图

2.所有的点出度入度相等或有且只有一个点出度比入度大1(出发点),一个点入度比出度大1(终止点)。

有向图寻找欧拉回路

1.连通图

2.所有的点出度等于入度。

本题是词语接龙的模型,等价于在有向图中判断是否存在欧拉路径。使用并查集判断图是否连通。

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>

using namespace std;

char str[1010];
int father[30],vis[30],n,in[30],out[30];

void init(){
    for(int i=0; i<30; i++){
        father[i] = i;
        vis[i] = 0;
        out[i] = 0;
        in[i] = 0;
    }
}

int find(int x){
    if(x == father[x])  return x;
    return find(father[x]);
}

int main(){
//    freopen("in.txt", "r", stdin);
    int cas;
    scanf("%d",&cas);
    while(cas--){
        init();
        scanf("%d",&n);
        for(int i=0; i<n; i++){
            scanf("%s",str);
            int x = str[0] - 'a',y = str[strlen(str) - 1] - 'a';
            father[x] = father[y] = find(x);
            vis[x] = vis[y] = 1;
            out[x]++,in[y]++;
        }
        int r = 0;
        for(int i=0; i<30; i++)
            if(vis[i] && i == father[i])    r++;
        if(r > 1){cout << "The door cannot be opened." << endl; continue;}
        int x = 0, y = 0, z = 0, flag = 1;
        for(int i=0; i<30; i++){
            if(vis[i] && in[i] != out[i]){
                if(in[i] - out[i] == 1) x++;
                else if(out[i] - in[i] == 1)    y++;
                else z++;
            }
        }
        if(z)   cout << "The door cannot be opened." << endl;
        else if((!x && !y) || (x == 1 && y == 1))   cout << "Ordering is possible." << endl;
        else    cout << "The door cannot be opened." << endl;
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值