Luogu P2731 騎馬修柵欄 Riding the Fences

圈套圈板子題,詳解推薦看這位大佬的博客:https://www.cnblogs.com/acxblog/p/7390301.html

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define forn(i,n) for(int i=0;i<n;i++)
#define for1(i,n) for(int i=1;i<=n;i++)
#define IO ios::sync_with_stdio(false);cin.tie(0)
const int maxn = 1e3+50;
#pragma GCC optimize(2)
vector<int>E[maxn];
int head[maxn],tot = 1,vis[maxn][maxn],tim[maxn],ans[maxn],cnt;
void init(){
    forn(i,maxn) head[i] = -1;
    tot = 1;
}
struct edge{    
    int nex,to;
}e[maxn<<1];
void add(int u,int v){
    e[tot].to = v;
    e[tot].nex = head[u];
    head[u] = tot++;
}
void dfs(int u){
    for(int i = head[u];i!=-1;i = e[i].nex){
        int v = e[i].to;
        if(!vis[u][v]) continue;
        vis[u][v]--,vis[v][u]--;
        dfs(v);
    }
    ans[++cnt] = u;
}

int main(){
    IO; 
    init();
    int n;cin>>n;
    forn(i,n){
        int u,v;cin>>u>>v;
        E[u].push_back(v);
        E[v].push_back(u);
        vis[u][v]++;
        vis[v][u]++;
        tim[u]++;
        tim[v]++;
    }
    for1(i,500) {
        sort(E[i].begin(),E[i].end());
        reverse(E[i].begin(),E[i].end());
    }
    for1(i,500)if(!E[i].empty()){
        for(auto &v:E[i]){
            add(i,v);
        }
    }
    bool ok = 1;
    for1(i,500) if(tim[i]&1){
        dfs(i);
        ok = 0;
        break;
    }
    if(ok) for1(i,500) if(!E[i].empty()){
        dfs(i);
        break;
    }
    for(int i = cnt;i>=1;i--) cout<<ans[i]<<'\n';
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章