跳到正文

个人记录

AtCoder - abc286_g

Chthohepta约 6 分钟
原文
文章信息与版本

文章信息

发布
2025年7月28日
收录
2025年12月12日
更新
2026年11月8日
篇幅
约 6 分钟

版本

  1. v1当前

题意

给定无向图,和边的子集,判断是否存在路径,使得子集中的所有边恰好经过一次。

思路

我们可以把不在子集里的边链接的点缩成一个点,然后直接判断新图是否为欧拉图。

代码

C++
#include <bits/stdc++.h>
using ll = long long;
using ld = long double;
using namespace std;
ll read(){ ll x = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-'){ f = -1; } ch = getchar(); } while(ch >= '0' && ch <= '9'){ x = x * 10 + ch - '0', ch = getchar(); } return x * f; }
void write(ll x) { if(x < 0){ putchar('-'), x = -x; } if(x > 9){ write(x / 10); } putchar(x % 10 + '0'); }
string reads(){ string s = ""; char ch = getchar(); while(ch != ' ' && ch != '\n'){ s += ch; ch = getchar(); } return s; }
void writes(string s){ for(int i = 0; i < s.size(); i ++){ putchar(s[i]); } }
ld readd(){ ld x = 0.0, f = 1.0; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-'){ f = -1.0; } ch = getchar(); } while(ch >= '0' && ch <= '9'){ x = x * 10 + ch - '0', ch = getchar(); } if(ch != '.'){ return x * f; } ld w = 10.0; ch = getchar(); while(ch >= '0' && ch <= '9'){ x = x + (ch - '0') / w; w *= 10.0; ch = getchar(); } return x * f; }
void writed(ld x){ write(ll(x)); if(x < 0) x = -x; x -= ll(x); if(x == 0){ return; } putchar('.'); while(x != 0){ x *= 10; putchar(ll(x) + '0'); x -= ll(x); } }

const int N = 2e5 + 3;
int n, m, u, v;
int k, x[N];

struct edge{
    struct E{
        int u, v, to, id;
    }e[N << 1];
    int ec, head[N];

    void jian_bian(int u, int v, int i){
        ec ++;
        e[ec] = {u, v, head[u], i};
        head[u] = ec;
    }
}e, e2;

int cnt = 1;

int fa[N], sz[N];
int Find(int x){
    if(fa[x] == x) return x;
    fa[x] = Find(fa[x]);
    return fa[x];
}
void change(int x, int y){
    int fx = Find(x), fy = Find(y);
    if(sz[fx] < sz[fy]){
        swap(fx, fy);
    }
    sz[fx] += sz[fy];
    fa[fy] = fx;
}

int du[N];

int main(){

    n = read(), m = read();
    for(int i = 1; i <= m; i ++){
        u = read(), v = read();
        e2.jian_bian(u, v, i), e2.jian_bian(v, u, i);
    }

    k = read();
    for(int i = 1; i <= k; i ++){
        x[i] = read();
    }
    sort(x + 1, x + 1 + k);

    for(int i = 1; i <= n; i ++){
        sz[i] = 1, fa[i] = i;
    }

    for(int i = 1; i <= e2.ec; i ++){
        if(e2.e[i].id == x[cnt]){
            i ++, cnt ++;
            continue;
        }
        u = e2.e[i].u, v = e2.e[i].v;
        if(Find(u) != Find(v)){
            change(u, v);
        }
    }

    for(int i = 1; i <= e2.ec; i ++){
        int fu = Find(e2.e[i].u), fv = Find(e2.e[i].v);
        if(fu != fv){
            e.jian_bian(fu, fv, e2.e[i].id);
            du[fv] ++;
        }
    }

    cnt = 0;
    for(int i = 1; i <= n; i ++){
        if(fa[i] != i) continue;
        if(du[i] & 1) cnt ++;
    }
    if(cnt == 0 || cnt == 2) writes("Yes");
    else writes("No");


    return 0;
}

原文