题目
luogu p3629 -> 传送门
题解
- 在不建立道路时,我们需要把每条边都经过一遍,那么我们要走的路程显然是边数 ∗ 2 *2 ∗2, 即 2 ∗ ( n − 1 ) 2*(n-1) 2∗(n−1)。
- 只修建一条道路时,这条路应建在直径的两个断点处,那么我们要走的路径长度即为 2 ∗ ( n − 1 ) − L + 1 2 * (n - 1) - L + 1 2∗(n−1)−L+1, 其中 L L L表示树的直径
- 修建第二条道路时,又会形成一个环,那么如果两条新道路所成的环不重叠,则答案继续减小,若重叠,则两个环重叠部分需经历两次, 那么我们得到如下算法 :
- 1、求树的直径 L 1 L1 L1,将 L 1 L1 L1上的边权赋值为 − 1 -1 −1
- 2、再求树的直径 L 2 L2 L2,答案即为 2 ( n − 1 ) − L 1 + 1 − L 2 + 1 = 2 ∗ n − L 1 − L 2 2(n - 1) - L1 + 1- L2 + 1 = 2 * n - L1 - L2 2(n−1)−L1+1−L2+1=2∗n−L1−L2
code
#include <bits/stdc++.h>
using namespace std;
const int SIZE = 2e5 + 100;
template<typename _T>
inline void read(_T &s) {
s = 0; _T w = 1, ch = getchar();
while (!isdigit(ch)) { if (ch == '-') w = -1; ch = getchar(); }
while (isdigit(ch)) { s = (s << 1) + (s << 3) + (ch ^ 48); ch = getchar(); }
s *= w;
}
template<typename _T>
inline void write(_T s) {
if (s < 0) putchar('-'), s = -s;
if (s > 9) write(s / 10);
putchar(s % 10 + '0');
}
int n, k, cnt, tot = 1, ans, st, ed;
int nex[SIZE << 1], lin[SIZE], ver[SIZE << 1], dis[SIZE], edge[SIZE], fa[SIZE], f[SIZE];
bool vis[SIZE];
queue <int> q;
inline void add(int from, int to, int dis) {
ver[++tot] = to;
nex[tot] = lin[from];
edge[tot] = dis;
lin[from] = tot;
}
inline void init() {
read(n); read(k);
for (int i = 1, x, y; i < n; ++i) {
read(x), read(y);
add(x, y, 1), add(y, x, 1);
}
}
int bfs(int s) {
memset(vis, false, sizeof(vis));
int loc = s;
fa[s] = 0;
vis[s] = true;
dis[s] = 0;
q.push(s);
while (!q.empty()) {
int u = q.front(); q.pop();
for (int i = lin[u]; i; i = nex[i]) {
int v = ver[i];
if (!vis[v]) {
vis[v] = true; q.push(v);
dis[v] = dis[u] + 1;
fa[v] = u;
if (dis[loc] < dis[v]) loc = v;
}
}
}
return loc;
}
void pre_work() {
st = bfs(1);
ed = bfs(st);
bfs(1);
memset(vis, false, sizeof(vis));
if (dis[st] < dis[ed]) swap(st, ed);
vis[st] = vis[ed] = true;
while (dis[st] > dis[ed]) {
st = fa[st];
vis[st] = true;
++cnt;
}
while (st != ed) {
st = fa[st];
ed = fa[ed];
vis[st] = vis[ed] = true;
cnt += 2;
}
}
void sign(int u) {
for (int i = lin[u]; i; i = nex[i]) {
int v = ver[i];
if (v != fa[u]) {
if (vis[v] && vis[u]) {
edge[i] = edge[i ^ 1] = -1;
}
sign(v);
}
}
}
void dp(int u) {
int _max = 0;
for (int i = lin[u]; i; i = nex[i]) {
int v = ver[i];
if (v != fa[u]) {
dp(v);
ans = max(ans, _max + f[v] + edge[i]);
_max = max(_max, f[v] + edge[i]);
}
}
ans = max(ans, _max);
f[u] = _max;
}
inline void output() {
if (k == 1) {
write(2 * (n - 1) - cnt + 1), putchar('\n');
exit(0);
}
if (cnt == n - 1) {
write(n + 1), putchar('\n');
exit(0);
}
sign(1);
dp(1);
write(2 * n - cnt - ans), putchar('\n');
}
int main() {
init();
pre_work();
output();
return 0;
}