POJ 1041 贪心 + 欧拉回路

题解

传送门 POJ 1041 John’s trip

题解

求字典序最小的欧拉回路。 D F S DFS DFS 求解欧拉回路时,贪心地先从编号小的边开始递归即可。

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int maxn = 50, maxm = 2000;
struct edge
{
    
    
    int to, cost;
    bool operator<(const edge &o) const {
    
     return cost < o.cost; }
};
vector<edge> G[maxn];
int S, it[maxn], nr, res[maxm];
bool vs[maxm];

inline void add(int x, int y, int z)
{
    
    
    G[x].push_back(edge{
    
    y, z});
    G[y].push_back(edge{
    
    x, z});
}

void euler(int x)
{
    
    
    for (int &i = it[x]; i < G[x].size(); ++i)
    {
    
    
        edge &e = G[x][i];
        if (!vs[e.cost])
            vs[e.cost] = 1, euler(e.to), res[++nr] = e.cost;
    }
}

int main()
{
    
    
    int x, y, z;
    while (~scanf("%d%d", &x, &y) && (x | y))
    {
    
    
        for (int i = 1; i < maxn; ++i)
            G[i].clear();
        memset(it, 0, sizeof(it));
        memset(vs, 0, sizeof(vs));
        S = min(x, y);
        scanf("%d", &z);
        add(x, y, z);
        while (~scanf("%d%d", &x, &y) && (x | y))
            scanf("%d", &z), add(x, y, z);
        bool f = 1;
        for (int i = 1; i < maxn; ++i)
            if (G[i].size() & 1)
                f = 0;
        if (!f)
        {
    
    
            puts("Round trip does not exist.");
            continue;
        }
        for (int i = 1; i < maxn; ++i)
            sort(G[i].begin(), G[i].end());
        nr = 0;
        euler(S);
        for (int i = nr; i; --i)
            printf("%d%c", res[i], i == 1 ? '\n' : ' ');
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/neweryyy/article/details/114992608