POJ1041

欧拉路问题

本次比赛的水题

对于这题的无向图,要每一个点的度数都为偶数,才存在欧拉回路。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int G[50][2000];  //G[点][边] = 点
bool vis[2000];
int degree[50];
int stack[2000], top;
int max(int a, int b)
{
    return a > b ? a : b;
}
void euler(int cur, int nRoads)
{
    for(int i = 1; i <= nRoads; i++)
    {
        if(!vis[i] && G[cur][i])
        {
            vis[i] = true;
            euler(G[cur][i], nRoads);
            stack[++top] = i;//找到路之后,再入栈
        }
    }
}
int main()
{
    int x, y, z, nRoads, nPoints, start;
    while(cin>>x>>y && x && y)
    {
        nRoads = nPoints = top = 0;
        memset(vis, false, sizeof(vis));
        memset(degree, 0, sizeof(degree));
        memset(G, 0, sizeof(G));
        start = x < y ? x : y;
        cin >> z;
        nRoads = max(nRoads, z);
        nPoints = max(nPoints, max(x, y));
        G[x][z] = y;
        G[y][z] = x;
        degree[x]++;
        degree[y]++;
        while(cin>>x>>y && x && y)
        {
            cin >> z;
            nRoads = max(nRoads, z);
            nPoints = max(nPoints, max(x, y));
            G[x][z] = y;
            G[y][z] = x;
            degree[x]++;
            degree[y]++;
        }
        bool flag = true;
        for(int i = 1; i <= nPoints; i++)//检查度数
            if(degree[i] %2)
                flag = false;
        if(!flag)
            cout << "Round trip does not exist." << endl;
        else
        {
            euler(start, nRoads);
            cout<<stack[top];
            for(int i = top - 1; i > 0; i--)
                cout<<" "<<stack[i];
            cout << endl;
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值