跳到正文

个人记录

POJ_1041题解

czhusi约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年8月14日
收录
2025年12月12日
更新
2026年11月19日
篇幅
约 3 分钟

版本

  1. v1当前

思路

约翰需要规划一条环形旅行路线,要求每条街道只走一次,最终回到起点。如果存在多条满足条件的路线,选择街道编号序列字典序最小的那条。如果不存在这样的路线,输出 "Round  trip  does  not  exist.""Round ~~ trip ~~ does ~~ not ~~ exist."。

要求每条街道只走一次并回到起点,本质是寻找无向图的欧拉回路。

注意到无向图存在欧拉回路的充要条件是所有顶点的度均为偶数,且图是连通的。

通过 dfsdfs 遍历边并标记走过的边,并在回溯时记录路径,在遍历时优先选择编号较小的街道,确保结果字典序最小即可。

代码

C++
#include <iostream>
#include <stack>
#include <cstring>

using namespace std;


const int N = 2e3 + 10, INF = 1e9;

int n, vis[N], incnt[50], mp[50][N];

stack<int> s;

void init(){
    n = 0;
    memset(vis, 0, sizeof(vis));
    memset(mp, 0, sizeof(mp));
    memset(incnt, 0, sizeof(incnt));
}

void dfs(int x){
    for(int i = 1; i <= n; ++i){
        if(mp[x][i] && !vis[i]){
            vis[i] = 1;
            dfs(mp[x][i]);
            s.push(i);
        }
    }
}

int main(){
    int first, x, y, w;
    while(cin >> x >> y && x && y){
        cin >> w;
        init();
        mp[x][w] = y;
        mp[y][w] = x;
        incnt[x]++, incnt[y]++;
        first = min(x, y);
        n = max(n, w);
        while(1){
            cin >> x >> y;
            if(!x && !y) break;
            cin >> w;
            mp[x][w] = y;
            mp[y][w] = x;
            incnt[x]++, incnt[y]++;
            n = max(n, w);
        }
        int tmp = 1;
        for(tmp = 1; tmp < 45; tmp++)if(incnt[tmp] % 2) break;
        if(tmp < 45){
            cout << "Round trip does not exist.\n";
        }else{
            dfs(first);
            while(s.size()){
                cout << s.top() << ' ';
                s.pop();
            }
            cout << '\n';
        }
    }
    return 0;
}
原文