UOJ117. 欧拉回路

分析:欧拉回路的模板题,不过要输出边的序号,那么在邻接表上稍微处理一下就好了.

#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>

using namespace std;

const int maxn = 100010, maxm = 400010;

vector <int> ans;
int n, m, cas, head[maxn], to[maxm], nextt[maxm], tot = 2,ru[maxn],chu[maxn],vis[maxm];

void add(int x, int y)
{
    to[tot] = y;
    nextt[tot] = head[x];
    head[x] = tot++;
}

void dfs(int u)
{
    for (int i = head[u]; i; i = nextt[i])
    {
        int v = to[i], c = (cas == 1 ? (i / 2) : (i - 1));
        bool flag = i & 1;
        if (vis[c])
            continue;
        vis[c] = 1;
        dfs(v);
        if (cas == 1)
            ans.push_back(flag ? -c : c);
        else
            ans.push_back(c);
    }
}

int main()
{
    scanf("%d%d%d", &cas, &n, &m);
    for (int i = 1; i <= m; i++)
    {
        int u, v;
        scanf("%d%d", &u, &v);
        chu[u]++;
        ru[v]++;
        if (cas == 1)
        {
            add(u, v);
            add(v, u);
        }
        else
            add(u, v);
    }
    if (cas == 1)
    {
        for (int i = 1; i <= n; i++)
            if ((ru[i] + chu[i]) & 1)
            {
            printf("NO
");
            return 0;
            }
    }
            else
            {
                for (int i = 1; i <= n; i++)
                    if (ru[i] != chu[i])
                    {
                    printf("NO
");
                    return 0;
                    }
            }
    for (int i = 1; i <= n; i++)
        if (head[i])
        {
        dfs(i);
        break;
        }
    if (ans.size() != m)
    {
        printf("NO");
        return 0;
    }
    printf("YES
");
    for (int i = m - 1; i >= 0; i--)
        printf("%d ", ans[i]);

    return 0;
}
原文地址:https://www.cnblogs.com/zbtrs/p/7532558.html