UVA 10129 Play on Words

UVA 10129 Play on Words

题目大意:判断首字母与末尾字母形成的若安路是否形成欧拉通路

解题思路:判断是否连通,然后判断度数是否为偶数(起点和终点入度和出度可以相差1)

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stack>
using namespace std;
stack<int> sta[26];
int m;
int in[26], out[26];
int flag[26];
int num;
int all;
void dfs(int a) {
    flag[a] = 0;
    num++;
    if(num == all)
        return;
    while(!sta[a].empty()) {
        int b = sta[a].top();
        if(flag[b] == 1) {
            dfs(b);
        }
        sta[a].pop();
    }
    return;
}
int main() {
    int n;
    cin >> n;
    while(n--) {
        for(int i = 0; i < 26; i++)
            while(!sta[i].empty())
                sta[i].pop();
        memset(in, 0, sizeof(in));
        memset(out, 0, sizeof(out));
        memset(flag, 0, sizeof(flag));
        int x, y;
        cin >> m;
        getchar();
        char ch[1000];
        all= 0;
        for(int i = 0; i < m; i++) {
            gets(ch);
            x = ch[0] - 'a';
            y = ch[strlen(ch)-1] - 'a';
            out[x]++;
            in[y]++;
            sta[x].push(y);
            sta[y].push(x);
            if(flag[x] == 0) {
                all++;
                flag[x] = 1;
            }
            if(flag[y] == 0) {
                all++;
                flag[y] = 1;
            }
        }
        num = 0;
        dfs(x);
        int fir = 0;
        int fin = 0;
        if(num == all) {
            for(int i = 0; i < 26; i++) {
                if(fir > 1)
                    break;
                if(fin > 1)
                    break;
                if(in[i] == out[i])
                    continue;
                if(in[i] - out[i] == 1)
                    fir++;
                else if(out[i] - in[i] == 1)
                    fin++;
                else {
                    num = -1;
                    break;
                }

            }
        }
        if(num == all && fir - fin == 0)
            printf("Ordering is possible.\n");
        else
            printf("The door cannot be opened.\n");

    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值