10129 - Play on Words (UVA)

题目链接如下:

Online Judge

欧拉道路的题。

有向图满足欧拉道路有两个条件:1,图是连通的(无向边意义上);2,最多只能有两个点的出度不等于入度,而且其中一个点的出度比入度大1,一个点的入度比出度大1.

连通是在无向边意义上连通,所以第16行需要 mat[k][i] || mat[i][k] ,只要单方向有路,就算连通。(一个测试数据:

msm

mac

csd

dsa

asd

如果 mat[k][i] || mat[i][k] 写成 mat[k][i] ,这组数据答案会有问题。

我的代码如下:

cpp 复制代码
#include <iostream>
#include <string>
#include <algorithm>
#include <map>
// #define debug

int T, N;
std::string str;
int degree[26];
int mat[26][26];
int visited[26];

void dfs(int k){
    visited[k] = 0;
    for (int i = 0; i < 26; ++i){
        if (visited[i] && (mat[k][i] || mat[i][k])){
            dfs(i);
        }
    }
}

int main(){
    #ifdef debug
    freopen("0.txt", "r", stdin);
    freopen("1.txt", "w", stdout);
    #endif
    scanf("%d", &T);
    while (T--){
        std::fill(degree, degree + 26, 0);
        std::fill(mat[0], mat[0] + 26 * 26, 0);
        std::fill(visited, visited + 26, 0);
        scanf("%d", &N);
        while (N--){
            std::cin >> str;
            degree[str[0] - 'a']++;
            degree[str.back() - 'a']--;
            mat[str[0] - 'a'][str.back() - 'a']++;
            visited[str[0] - 'a'] = 1;
            visited[str.back() - 'a'] = 1;
        }
        std::map<int, int> mp;
        bool flag = true;
        for (int i = 0; i < 26; ++i){
            if (degree[i] < -1 || degree[i] > 1){
                flag = false;
                break;
            }
            if (degree[i] == -1){
                mp[-1]++;
            } else if (degree[i] == 1){
                mp[1]++;
            }
        }
        if (!flag || mp[-1] > 1 || mp[1] > 1 || mp[-1] != mp[1]){
            printf("The door cannot be opened.\n");
            continue;
        }
        int cnt = 0;
        for (int i = 0; i < 26; ++i){
            if (visited[i]){
                cnt++;
                dfs(i);
            }
        }
        if (cnt == 1){
            printf("Ordering is possible.\n");
        } else {
            printf("The door cannot be opened.\n");
        }
    }
    #ifdef debug
    fclose(stdin);
    fclose(stdout);
    #endif
    return 0;
}
相关推荐
松涛和鸣33 分钟前
11.C 语言学习:递归、宏定义、预处理、汉诺塔、Fibonacci 等
linux·c语言·开发语言·学习·算法·排序算法
2501_941111242 小时前
C++与自动驾驶系统
开发语言·c++·算法
2501_941111692 小时前
C++中的枚举类高级用法
开发语言·c++·算法
jz_ddk3 小时前
[算法] 算法PK:LMS与RLS的对比研究
人工智能·神经网络·算法·信号处理·lms·rls·自适应滤波
Miraitowa_cheems3 小时前
LeetCode算法日记 - Day 106: 两个字符串的最小ASCII删除和
java·数据结构·算法·leetcode·深度优先
旭编3 小时前
小红的好矩形
c++·算法
小白程序员成长日记3 小时前
2025.11.12 力扣每日一题
算法·leetcode·职场和发展
Alex艾力的IT数字空间3 小时前
设计既保持高性能又兼顾可移植性的跨平台数据结构
数据结构·分布式·算法·微服务·中间件·架构·动态规划
leoufung3 小时前
贪心算法核心定理与应用——以 Gas Station 问题为例
算法·贪心算法
2501_941111463 小时前
C++与硬件交互编程
开发语言·c++·算法