uoj#117. 歐拉回路

題面在這裏

題意:

求有向圖和無向圖的歐拉回路。

做法:

【模板】
具體做法自己百度。。

代碼:

/*************************************************************
    Problem: uoj#117. 歐拉回路
    User: bestFy
    Language: C++
    Result: Accepted
    Time: 401ms
    Memory: 12816kb
    Submit_Time: 2018-01-24 09:51:43
*************************************************************/

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cctype>
#include<cstdlib>
#include<cmath>
using namespace std;
typedef long long ll;

inline ll read() {
    char ch = getchar(); ll x = 0; int op = 1;
    for(; !isdigit(ch); ch = getchar()) if(ch == '-') op = -1;
    for(; isdigit(ch); ch = getchar()) x = x*10+ch-'0';
    return x*op;
}
inline void write(ll a) {
    if(a < 0) putchar('-'), a = -a;
    if(a >= 10) write(a/10); putchar('0'+a%10);
}

const int N = 100010, M = 200010;
int n, m, tot, cnt, st;
int head[N], vis[M], ans[M<<1], in[N], out[N];
struct edge {
    int to, nxt, id;
    edge() {}
    edge(int x, int y, int z) { to = x, nxt = y, id = z; }
}e[M<<1];

inline void gg() { puts("NO"); exit(0); }
inline void addedge(int x, int y, int z) { e[++ cnt] = edge(y, head[x], z); head[x] = cnt; }
inline void dfs(int u) {
    for(int i = head[u]; i; i = e[i].nxt) if(!vis[abs(e[i].id)]) {
        head[u] = i;
        vis[abs(e[i].id)] = 1;
        dfs(e[i].to);
        ans[++ tot] = e[i].id;
        i = head[u];
    }
}
int main() {
    int t = read(); n = read(); m = read();
    if(t == 1) {//無向圖
        for(int i = 1; i <= m; i ++) {
            int x = read(), y = read();
            addedge(x, y, i); addedge(y, x, -i);
            in[x] ++; in[y] ++; st = x;
        }
        for(int i = 1; i <= n; i ++) if(in[i]&1) gg();
        dfs(st); if(tot < m) gg();
        puts("YES");
        for(int i = m; i >= 1; i --) printf("%d ", ans[i]);
    } else {//有向圖
        for(int i = 1; i <= m; i ++) {
            int x = read(), y = read();
            addedge(x, y, i); in[y] ++; out[x] ++; st = x;
        }
        for(int i = 1; i <= n; i ++) if(in[i] != out[i]) gg();
        dfs(st); if(tot < m) gg();
        puts("YES");
        for(int i = m; i >= 1; i --) printf("%d ", ans[i]);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章