专栏首页ACM算法日常UVA10129:Play on Words(欧拉回路)

UVA10129:Play on Words(欧拉回路)

Some of the secret doors contain a very interesting word puzzle. The team of archaeologists has to solve it to open that doors. Because there is no other way to open the doors, the puzzle is very important for us.

一些密门会包含有趣的文字谜,考古学家小队为了开门不得不解决它。别无他法,谜题对我们很重要。

There is a large number of magnetic plates on every door. Every plate has one word written on it. The plates must be arranged into a sequence in such a way that every word begins with the same letter as the previous word ends. For example, the word ‘acm’ can be followed by the word ‘motorola’. Your task is to write a computer program that will read the list of words and determine whether it is possible to arrange all of the plates in a sequence (according to the given rule) and consequently to open the door.

每个门上会有大量磁盘且每个磁盘会有一个单词刻于其上。磁盘必须以此为序进行安排:每个单词的首字母必须与上一个单词的尾字母相同。例如“acm”后面可接“motorola”。你的任务就是写个程序来读入这些单词并判断是否有可能把它们安排明白以开门。

Input The input consists of T test cases. The number of them (T) is given on the first line of the input file. Each test case begins with a line containing a single integer number N that indicates the number of plates (1 ≤ N ≤ 100000). Then exactly N lines follow, each containing a single word. Each word contains at least two and at most 1000 lowercase characters, that means only letters ‘a’ through ‘z’ will appear in the word. The same word may appear several times in the list.

输入:第一行输入T代表会有T组测试数据。接下来每组会以一个整数N开始,暗示了会有N个磁盘(1 ≤ N ≤ 10万)。接下来的N行每行一个单词,单词包含2~1000个小写字母。相同的单词是可以多次出现的。

Output Your program has to determine whether it is possible to arrange all the plates in a sequence such that the first letter of each word is equal to the last letter of the previous word. All the plates from the list must be used, each exactly once. The words mentioned several times must be used that number of times. If there exists such an ordering of plates, your program should print the sentence ‘Ordering is possible.’. Otherwise, output the sentence ‘The door cannot be opened.’

输出:对于每组数据,所有的单词必须都要用上,某单词出现了几次就要用几次。如果可以穿成一串,就是存在一种可能的顺序,打印语句“Ordering is possible.”;否则打印“The door cannot be opened.”

Sample Input 3

2

acm

ibm

3

acm

malform

mouse

2

ok

ok

Sample Output The door cannot be opened.

Ordering is possible.

The door cannot be opened.

介绍:欧拉回路

如果图G中的一个路径包括每个边恰好一次,则该路径称为欧拉路径(Euler path)。

如果一个回路是欧拉路径,则称为欧拉回路(Euler circuit)。

欧拉回路是数学家欧拉在研究著名的德国哥尼斯堡(Koenigsberg)七桥问题时发现的。如图所示,流经哥尼斯堡的普雷格尔河(Pregel)中有两个岛,两个岛与两岸共4处陆地通过7座桥彼此相联。7桥问题就是:是否存在一条路线,可以不重复地走遍7座桥。

欧拉大佬把七桥问题改写成了图。则问题变成了:能否从无向图中的一个结点出发走出一条道路,每条边恰好经过一次。这样的路线就叫欧拉路径,也可以形象地称为“一笔画”。

不难发现,在欧拉道路中,进和出是对应的——除了起点和终点外,其他点的进出次数应该相等。换句话说,其他点的度数(degree)应该是偶数(我们把进入称为入度,出去称为出度)。在七桥问题中,所有4个点的度数均是奇数(这样的点称为奇点),因此不可能存在欧拉道路。

在此不加证明地给出欧拉道路和回路的存在条件,请结合生活实际验证:

那么介绍到这里,应该就可以自己动手编写这道欧拉路径的裸题了,先判断度数,再判断连通性即可。建议自己实现,有问题再参考别人程序。

此处给出两种判断连通性的代码,由于DFS和并查集都是基础算法,暂时不做冗余介绍~

DFS:

#include <bits/stdc++.h>
using namespace std;

string str;
int test, n;
int ru[26], chu[26];//入度和出度
bool table[26][26], vis[26];

bool dfs(int cur)
{
    vis[cur] = true;
    for (int i = 0; i < 26; i++)
        if (cur != i && table[cur][i] && !vis[i])
            dfs(i);
}

bool ok()
{
    for (int i = 0; i < 26; i++)
        if (vis[i])
            n--;
    return n == 0;
}

int main()
{
    cin >> test;
    while (test--)
    {
        //初始化
        memset(table, false, sizeof(table));
        memset(vis, false, sizeof(vis));
        memset(ru, 0, sizeof(ru));
        memset(chu, 0, sizeof(chu));
        //输入
        cin >> n;
        for (int i = 1; i <= n; i++)
        {
            cin >> str;
            int x = str[0] - 'a', y = str[str.length()-1] - 'a';
            table[x][y] = table[y][x] = true;//邻接矩阵制作无向图
            chu[x]++;
            ru[y]++;
        }
        //计算度数是否符合条件
        int a = 0, b = 0, c = -1, d = 0;
        n = 26;
        for (int i = 0; i < 26; i++)
        {
            if (ru[i] == chu[i])
            {
                a++;
                if (!ru[i])//用来判定最后出现了几个字母
                    n--;
            }
            else if (ru[i] == chu[i]-1) b++, c = i;
            else if (ru[i] == chu[i]+1) d++;
        }

        if ((b == 1 && d == 1 && a == 24) || a == 26)
        {
            if (c == -1)//即a==26时
                for (int i = 0; i < 26; i++)
                    if (chu[i])
                    {
                        c = i;
                        break;
                    }
            dfs(c);
            if (ok())
            {
                puts("Ordering is possible.");
                continue;
            }
        }
        puts("The door cannot be opened.");
    }
    return 0;
}

本文分享自微信公众号 - ACM算法日常(acm-clan)

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2018-08-06

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 搜索专题4 | 旋转棋盘 POJ - 2286

    The rotation game uses a # shaped board, which can hold 24 pieces of square bloc...

    ACM算法日常
  • 独角兽与数列(置换群循环)- HDU 4985

    群论是法国数学家伽罗瓦(Galois)的发明。伽罗瓦是一个极具传奇性的人物,年仅21岁就英年早逝于一场近乎自杀的决斗中。他用该理论,具体来说是伽罗瓦群,解决了五...

    ACM算法日常
  • 除以3,乘以2(STL+排序)- Codeforces 997D

    Polycarp likes to play with numbers. He takes some integer number x, writes it d...

    ACM算法日常
  • SAP Hybris和CRM WebUI里UI模型的类比

    Jerry Wang
  • Spring_总结_04_高级配置(二)之条件注解@Conditional

    在上一节,我们了解到 Profile 为不同环境下使用不同的配置提供了支持,那么Profile到底是如何实现的呢?其实Profile正是通过条件注解来实现的。

    shirayner
  • Codeforces Round #624 (Div. 3) C - Perform the Combo

    You want to perform the combo on your opponent in one popular fighting game. The...

    glm233
  • 无限视距微分模型预测控制(CS SC)

    本文提出了一种用于安全仿学习的可微线性二次模型预测控制(MPC)框架。 使用从离散时间代数Riccati方程(DARE)获得的终端成本函数强制执行无限水平成本,...

    非过度曝光
  • matplotlib.collections、(二)

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 ...

    于小勇
  • 以太坊 Iban 地址

    中国广东省深圳市龙华新区民治街道溪山美地 518131 +86 13113668890 <netkiller@msn.com>

    netkiller old
  • HDUOJ---Piggy-Bank

    Piggy-Bank Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K...

    Gxjun

扫码关注云+社区

领取腾讯云代金券