pku1386

/*
 * File:   pku1386.cpp
 * 欧拉回路,判断是否有欧拉回路或者是欧拉路径
 * 有向图有欧拉回路的充要条件是图必须是联通的,而且节点的出度等于入度
 * 有向图有欧拉路径的充要条件是图必须是联通的,而且仅有一个点的出度比入度
 * 大1,仅有一个点的入度比出度大1,其他点的入度等于出度
 *
 * 建图:首字母连一条有向边到末字母,首字母出度加一,末尾字母入度加一
 *
 * dfs判断是否是联通的,然后再判断度的关系
 * Author: chenjiang
 *
 * Created on 2010年5月11日, 下午7:56
 */

#include <stdlib.h>
#include <iostream>
#include <vector>
#include <string.h>
#include <stdio.h>
using namespace std;
#define _max 30
vector<int>v[_max];
int in[_max];
int out[_max];
char ch[1005];
bool visited[_max];
int ans;
int n;

/*
 *
 */
void dfs(int k) {
    int i;
    ans++;
    visited[k] = 1;
    for (i = 0; i < v[k].size(); i++) {
        if (!visited[v[k][i]])
            dfs(v[k][i]);
    }
}

int main(int argc, char** argv) {

    int i, j;
    int T;
    cin >> T;
    while (T--) {
        cin >> n;
        for (i = 0; i < 26; i++)//初始化
        {
            in[i] = 0;
            out[i] = 0;
            v[i].clear();
            visited[i] = 0;
        }

        for (i = 1; i <= n; i++) {
            cin >> ch;
            int a = ch[0] - 'a';
            int b = ch[strlen(ch) - 1] - 'a';
            v[a].push_back(b);
            in[b]++;
            out[a]++;
        }

        int s1, s2, s3;
        int num = 0;
        s1 = 0;
        s2 = 0;
        s3 = 0;
        int start, end;
        for (i = 0; i < 26; i++) {
            if (in[i] + out[i] != 0) {
                num++;
                if (in[i] + 1 == out[i]) {
                    s1++;
                    start = i;
                } else if (in[i] == out[i]) {
                    s2++;
                } else if (out[i] + 1 == in[i]) {
                    s3++;
                }
                end = i;
            }
        }
        ans = 0;
        if (s1 != 0)dfs(start);
        else dfs(end);
        if (num == ans) {
            if ((s1 == 1 && s3 == 1 && s2 == num - 2) || s2 == num) {
                cout << "Ordering is possible." << endl;
            } else {
                cout << "The door cannot be opened." << endl;
            }
        } else {
            cout << "The door cannot be opened." << endl;
        }
    }
    return (EXIT_SUCCESS);
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值