欧拉路与欧拉回路

https://www.acwing.com/problem/content/submission/code_detail/4121247/

知识点

#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define ull unsigned long long
#define pb push_back
#define PII pair<int, int>
#define VIT vector<int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 100010, M = 400010;
int type;
int n, m;
int h[N], e[M], ne[M], idx;
bool used[M];
int ans[M], cnt;
int din[N], dout[N];

void add(int a, int b) {
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

void dfs(int u) {
    for (int &i = h[u]; ~i;) {
        if (used[i]) {
            i = ne[i];
            continue;
        }
        used[i] = 1;
        if (type == 1) used[i ^ 1] = 1;
        int t;
        if (type == 1) {
            t = i / 2 + 1;
            if (i & 1) t = -t;
        } else t = i + 1;
        int j = e[i];
        i = ne[i];
        dfs(j);
        ans[++cnt] = t;
    }
}

int main() {
    //IO;
    cin >> type;
    cin >> n >> m;
    memset(h, -1, sizeof h);
    for (int i = 0; i < m; ++i) {
        int a, b;
        cin >> a >> b;
        add(a, b);
        if (type == 1) add(b, a);
        din[b]++, dout[a]++;
    }
    if (type == 1) {
        for (int i = 1; i <= n; ++i) 
            if (din[i] + dout[i] & 1) {
                puts("NO");
                return 0;
            }
    }
    else {
        for (int i = 1; i <= n; ++i)
            if (din[i] != dout[i]) {
                puts("NO");
                return 0;
            }
    }
    for (int i = 1; i <= n; ++i)
        if (h[i] != -1) {
            dfs(i);
            break;
        }
    if (cnt < m) {
        puts("NO");
        return 0;
    }
    puts("YES");
    for (int i = cnt; i; --i) cout << ans[i] << ' ';
    puts("");
    return 0;                
}



posted @ 2021-02-24 21:04  phr2000  阅读(47)  评论(0编辑  收藏  举报