luogu:https://www.luogu.com.cn/problem/P7771

求有向图字典序最小的欧拉路径。
如果不存在欧拉路径,输出一行 No。
否则输出一行 \(m\) + 1 个数字,表示字典序最小的欧拉路径。

#include <bits/stdc++.h>
using namespace std;
#define LL long long
const int N = 1e5 + 10;
LL n, m, in[N], out[N];
vector <LL> p(N);
vector < pair<LL, LL> > g[N];
stack <LL> ans;
void dfs(LL u){
	for (int i = p[u]; i < (int)g[u].size(); i = max(i + 1LL, p[u]) ){
		auto [v, vis] = g[u][i];
		p[u] = i + 1;
		dfs(v);
	}
	ans.push(u);
};
int main(){
	ios::sync_with_stdio(false);cin.tie(0);
	cin >> n >> m;
	for (int i = 0; i < m; i ++ ){
		LL u, v;
		cin >> u >> v;
		g[u].push_back({v, i});
		out[u] ++ ;
		in[v] ++ ;
	}
	LL st = 0, ed = 0, s = 1;
	bool ok = true;
	for (int i = 1; i <= n; i ++ ){
		sort(g[i].begin(), g[i].end());
		if (in[i] != out[i]){
			if (in[i] == out[i] + 1){
				ed ++ ;
			}
			else if (out[i] == in[i] + 1){
				st ++ ;
				s = i;
			}
			else{
				ok = false;
				break;
			}
		}
	}
	if ( (st == 1 && ed == 1 && ok) || (!st && !ed && ok) ){
		dfs(s);
		while (ans.size()){
			cout << ans.top() << " ";
			ans.pop();
		}
	}
	else{
		cout << "No\n";
	}
	return 0;
}
posted on 2022-07-03 15:05  Hamine  阅读(25)  评论(0编辑  收藏  举报