记录编号 |
576993 |
评测结果 |
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
题目名称 |
[APIO 2010]巡逻 |
最终得分 |
100 |
用户昵称 |
HeSn |
是否通过 |
通过 |
代码语言 |
C++ |
运行时间 |
1.684 s |
提交时间 |
2022-10-19 22:19:39 |
内存使用 |
11.16 MiB |
显示代码纯文本
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 100010;
int n, k, ans, maxn, rt, vis[MAXN], fa[MAXN], f[MAXN], flg;
vector<int>cd[MAXN], w[MAXN];
void dfs(int x, int s, int fath) {
// cout << x << ' ' << s << endl;;
if(s > maxn) {
maxn = s;
rt = x;
}
for(int i = 0; i < cd[x].size(); i ++) {
int u = cd[x][i];
if(u == fath) {
continue;
}
if(flg) {
fa[u] = x;
}
dfs(u, s + 1, x);
}
}
void dp(int x, int fath) {
for(int i = 0; i < cd[x].size(); i ++) {
int u = cd[x][i];
if(u == fath) {
continue;
}
dp(u, x);
ans = max(ans, f[x] + f[u] + w[x][i]);
f[x] = max(f[x], f[u] + w[x][i]);
}
}
signed main() {
freopen("xunluo.in", "r", stdin);
freopen("xunluo.out", "w", stdout);
cin >> n >> k;
for(int i = 1; i < n; i ++) {
int x, y;
cin >> x >> y;
cd[x].push_back(y);
cd[y].push_back(x);
w[x].push_back(1);
w[y].push_back(1);
}
dfs(1, 0, 0);
flg = 1;
// cout << rt << endl;
maxn = 0;
dfs(rt, 0, 0);
// cout << rt << endl;
if(k == 1) {
cout << n * 2 - maxn - 1;
return 0;
}
// cout << maxn << endl;
ans = n * 2 - maxn;
int x = rt;
// for(int i = 1; i <= n; i ++) {
// cout << fa[i] << ' ';
// }
while(fa[x]) {
// cout << x << endl;
for(int i = 0; i < cd[fa[x]].size(); i ++) {
int u = cd[fa[x]][i];
if(u == x) {
w[fa[x]][i] = -1;
break;
}
}
for(int i = 0; i < cd[x].size(); i ++) {
int u = cd[x][i];
if(u == fa[x]) {
w[x][i] = -1;
break;
}
}
x = fa[x];
}
x = ans;
ans = 0;
dp(1, 0);
// cout << ans << ' ' << x << endl;
cout << x - ans;
return 0;
}