jzoj 6838. 2020.10.31【NOIP提高A组】T4 小j 的组合

考虑将操作转变为每个点可经过次数\(+1\),设每个点可经过次数为\(e[i]\),那答案即为\(\sum (e[i]-1)\)
当每个点的可经过次数等于该点度数的时候,才应当是最优解。
我们可以通过求直径,然后从直径一端开始跑,先跑非直径边后直接走直径,这样最优。
由于每条非直径的边走完以后还要返回到父亲节点,所以答案\(g\)即为\(n-直径节点个数\)

#include <cstdio>
#define N 210
#define db double
#define ll long long
#define mem(x, a) memset(x, a, sizeof x)
#define mpy(x, y) memcpy(x, y, sizeof y)
#define fo(x, a, b) for (int x = (a); x <= (b); x++)
#define fd(x, a, b) for (int x = (a); x >= (b); x--)
#define go(x) for (int p = tail[x], v; p; p = e[p].fr)
using namespace std;
struct node{int v, fr;}e[N << 1];
int n, tail[N], cnt = 0, fd = 0, rt, mln = 0;
int p_[N << 2], tot = 0, num, u[N], cz = 0, fa[N];

inline int read() {
	int x = 0, f = 0; char c = getchar();
	while (c < '0' || c > '9') f = (c == '-') ? 1 : f, c = getchar();
	while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
	return f ? -x : x;
}

inline void add(int u, int v) {e[++cnt] = (node){v, tail[u]}; tail[u] = cnt;}

void dfs(int x, int len, int fat) {
	if (len > mln) mln = len, fd = x;
	go(x) {
		if ((v = e[p].v) == fat) continue;
		fa[v] = x, dfs(v, len + 1, x);
	}
}

void solve(int x, int fro) {
	p_[++tot] = x;
	go(x) {
		if ((v = e[p].v) == fro || v == fa[x]) continue;
		solve(v, x), p_[++tot] = ++num, u[++cz] = x;
	}
	if (fa[x] && fa[x] != fro) solve(fa[x], x);
}

int main()
{
	freopen("combo.in", "r", stdin);
	freopen("combo.out", "w", stdout);
	n = read();
	fo(i, 2, n) {
		int u = read(), v = read();
		add(u, v), add(v, u);
	}
	dfs(1, 1, 0), rt = fd;
	mln = fd = 0, fa[rt] = 0;
	dfs(rt, 1, 0);
	printf("%d\n", n - mln);
	num = n, solve(fd, 0);
	fo(i, 1, cz) printf("%d ", u[i]);
	printf("\n");
	fo(i, 1, tot) printf("%d ", p_[i]);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值