首页 > 代码库 > bzoj 1912 : [Apio2010]patrol 巡逻 树的直径

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 secondtypedef complex <double> cmx;typedef pair<int, int> pll;const double PI = acos(-1.0);const double eps = 1e-8;const int mod = 1e9+7;const int inf = 1061109567;const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };const int maxn = 1e5+5;int head[maxn], num, mx1[maxn], mx2[maxn], n, maxx, p;struct node{    int to, nextt, val;}e[maxn*2];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 = 0;    mem1(head);}int dfs(int u, int fa){    int maxx1 = 0, maxx2 = 0;    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 = 0; i < n - 1; i ++) {        scanf("%d%d", &u, &v);        add(u, v, 1);        add(v, u, 1);    }    dfs(1, 0);    int ans = 2*(n-1);    ans -= (maxx - 1);    if(k == 2) {        for(int i = mx1[p]; i; i = mx1[e[i].to]) e[i].val = e[i^1].val = -1;        for(int i = mx2[p]; i; i = mx1[e[i].to]) e[i].val = e[i^1].val = -1;        maxx = 0;        dfs(1, 0);        ans -= (maxx-1);    }    cout<<ans<<endl;    return 0;}

 

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