【模板】欧拉路径
题目跳转
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
uint8_t buf[1<<20],*p1,*p2;
#define gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<20,stdin),p1==p2)?EOF:*p1++)
ll rd(){
ll x=0,f=1,ch=gc();
while(ch<'0'||ch>'9'){
if(ch=='-'){
f=-1;
}
ch=gc();
}
while(ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+(ch-'0');
ch=gc();
}
return x*f;
}
void write(ll x){
if(x<0){
x*=-1;
putchar('-');
}
if(x>9){
write(x/10);
}
putchar(x%10+'0');
}
const ll maxn=1e5+5;
ll n,m,rt=1,ru[maxn],chu[maxn],cnt[2],st[maxn];
bool flag;
struct node{
ll v;
bool vis;
};
vector<node> e[maxn];
stack<ll> stk;
bool cmp(node x,node y){
return x.v<y.v;
}
void dfs(ll x){
for(ll i=0;i<e[x].size();i=max(i+1,st[x])){
if(!e[x][i].vis){
e[x][i].vis=true;
st[x]=i+1;
dfs(e[x][i].v);
}
}
stk.push(x);
}
int main(){
n=rd();
m=rd();
for(ll i=1;i<=m;i++){
ll u=rd(),v=rd();
e[u].push_back({v,false});
chu[u]++;
ru[v]++;
}
for(ll i=1;i<=n;i++){
if(ru[i]!=chu[i]){
flag=true;
if(ru[i]-chu[i]==1){
cnt[0]++;
}else if(chu[i]-ru[i]==1){
cnt[1]++;
rt=i;
}else{
printf("No");
return 0;
}
}
}
if(flag&&!(cnt[0]==cnt[1]&&cnt[0]==1)){
printf("No");
}else{
for(ll i=1;i<=n;i++){
sort(e[i].begin(),e[i].end(),cmp);
}
dfs(rt);
while(!stk.empty()){
write(stk.top());
putchar(' ');
stk.pop();
}
}
return 0;
}
Goodbye!

浙公网安备 33010602011771号