CF29C 题解

思路

既然这题没有环,又要用到所有的边,这不就是一条链嘛!直接找到任意一个度为 11 的点作为起点后 dfs 一次,因为是一条链,所以 dfs 途中只要不走回头路就一定是一次就找到答案,时间复杂度 O(n)O(n)

代码

# include <bits/stdc++.h>
typedef long long ll;
using namespace std;
int n, du[100005], s, ans[100005], x, y, a[100005],tot;
bitset <100005> vis;
vector <int> v[100005];
map <int, int> mp;
void dfs (int x, int step) {
	ans[step] = x;
	if (step > n) {
		for (int i = 1; i <= step; ++ i)
			cout << a[ans[i]] << ' ';
		exit (0);
	}
	for (int& i : v[x])
		if (! vis[i])
			vis[i] = 1, dfs (i, step + 1), vis[i] = 0;
	return ;
}
int main () {
	ios::sync_with_stdio (0);
	cin.tie (0);
	cout.tie (0);
	cin >> n;
	for (int i = 0; i < n; ++ i) {
		cin >> x >> y;
		if (mp[x])
			x = mp[x];
		else
			mp[x] = ++ tot, a[tot] = x, x = tot;
		if (mp[y])
			y = mp[y];
		else
			mp[y] = ++ tot, a[tot] = y, y = tot;
		++ du[x];
		++ du[y];
		v[x].emplace_back (y);
		v[y].emplace_back (x);
	}
	for (int i = 1; i <= tot; ++ i)
		if (du[i] & 1) {
			s = i;
			break ;			
		}
	vis[s] = 1;
	dfs (s, 1);
	return 0;
}
posted @ 2024-04-29 15:16  Vitamin_B  阅读(29)  评论(0)    收藏  举报  来源