bzoj 1912 : [Apio2010]patrol 巡逻 树的直径

题目链接

如果k==1, 显然就是直径。

k==2的时候, 把直径的边权变为-1, 然后在求一次直径。 变为-1是因为如果在走一次这条边, 答案会增加1.

学到了新的求直径的方法...

#include <bits/stdc++.h>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define lson l, m, rt<<1
#define mem(a) memset(a, 0, sizeof(a))
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, n, a) for(int i = a; i<n; i++)
#define fi first
#define se second
typedef complex <double> cmx;
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const double eps = 1e-;
const int mod = 1e9+;
const int inf = ;
const int dir[][] = { {-, }, {, }, {, -}, {, } };
const int maxn = 1e5+;
int head[maxn], num, mx1[maxn], mx2[maxn], n, maxx, p;
struct node
{
int to, nextt, val;
}e[maxn*];
void add(int u, int v, int val) {
e[num].to = v, e[num].nextt = head[u], e[num].val = val, head[u] = num++;
}
void init() {
num = ;
mem1(head);
}
int dfs(int u, int fa)
{
int maxx1 = , maxx2 = ;
for(int i = head[u]; ~i; i = e[i].nextt) {
int v = e[i].to;
if(v == fa)
continue;
int tmp = e[i].val + dfs(v, u);
if(tmp > maxx1) {
maxx2 = maxx1;
maxx1 = tmp;
mx2[u] = mx1[u];
mx1[u] = i;
} else if(tmp > maxx2) {
maxx2 = tmp;
mx2[u] = i;
}
}
if(maxx < maxx1 + maxx2) {
maxx = maxx1+maxx2;
p = u;
}
return maxx1;
}
int main()
{
int k, u, v;
cin>>n>>k;
init();
for(int i = ; i < n - ; i ++) {
scanf("%d%d", &u, &v);
add(u, v, );
add(v, u, );
}
dfs(, );
int ans = *(n-);
ans -= (maxx - );
if(k == ) {
for(int i = mx1[p]; i; i = mx1[e[i].to]) e[i].val = e[i^].val = -;
for(int i = mx2[p]; i; i = mx1[e[i].to]) e[i].val = e[i^].val = -;
maxx = ;
dfs(, );
ans -= (maxx-);
}
cout<<ans<<endl;
return ;
}
上一篇:bzoj 3302&2447&2103 树的双中心 树形DP


下一篇:非正常关闭myeclicps后,出现错误Errors occurred during the build.的解决方法