【BZOJ1912】【APIO2010】巡逻(树最长链)

来源:互联网 发布:颖儿减肥方法知乎 编辑:程序博客网 时间:2024/06/06 02:52

Description

这里写图片描述

Input

第一行包含两个整数 n, K(1 ≤ K ≤ 2)。接下来 n – 1行,每行两个整数 a, b, 表示村庄a与b之间有一条道路(1 ≤ a, b ≤ n)。

Output

输出一个整数,表示新建了K 条道路后能达到的最小巡逻距离。

Sample Input

8 1

1 2

3 1

3 4

5 3

7 5

8 5

5 6

Sample Output

11

HINT

10%的数据中,n ≤ 1000, K = 1;
30%的数据中,K = 1;
80%的数据中,每个村庄相邻的村庄数不超过 25;
90%的数据中,每个村庄相邻的村庄数不超过 150;
100%的数据中,3 ≤ n ≤ 100,000, 1 ≤ K ≤ 2。

题解:
神题!
首先考虑k=0的情况,显然是每条边走2遍,答案为(n-1)*2。
如果是k=1,贪心的想,就是把树的最长链的两端连起来,答案为(n-1)*2-len(最长链)+1。
如果是k=2呢?
把原来最长链上的边权标为-1,再做最长链,答案为(n-1)*2-len(最长链)+1-len(最长链2)+1。
为什么是对的呢?
第一次算这条边的时候加了1,第二次的时候加的是-1,相当于是这条边没有贡献,相当于是把两条交错的链变成了两条分开的链。
确实是一个神奇的做法呢。

代码如下:

#include<iostream>#include<stdio.h>#include<algorithm>#include<string.h>#include<math.h>#define ll long long#define inf 0x7f7f7f7f#define N 100005using namespace std;int read(){    int x=0,f=1;    char ch=getchar();    while(ch<'0' || ch>'9') {if(ch=='-') f=-1;ch=getchar();}    while(ch>='0' && ch<='9') {x=x*10+ch-'0';ch=getchar();}    return x*f;}int mx,n,K,tot,cnt,di;int hd[N],s1[N],s2[N];struct edge{    int to,nex,v;       }e[N<<1];void insert(int u,int v){    e[++cnt]=(edge){v,hd[u],1};hd[u]=cnt;    e[++cnt]=(edge){u,hd[v],1};hd[v]=cnt;}int dfs(int x,int fa){    int mx1=0,mx2=0;    for(int i=hd[x];i;i=e[i].nex)    if(e[i].to!=fa)    {        int v=e[i].v+dfs(e[i].to,x);        if(v>mx1)         {            mx2=mx1,mx1=v;            s2[x]=s1[x],s1[x]=i;        }        else if(v>mx2) mx2=v,s2[x]=i;    }    if(mx1+mx2>di) di=mx1+mx2,mx=x;    return mx1;}int main(){    n=read(),K=read();    tot=(n-1)<<1;    for(int i=1,u,v;i<n;i++) u=read(),v=read(),insert(u,v);    dfs(1,0);    tot=tot-di+1;    if(K==2)    {        di=0;        for(int i=s1[mx];i;i=s1[e[i].to]) e[i].v=e[i^1].v=-1;        for(int i=s2[mx];i;i=s1[e[i].to]) e[i].v=e[i^1].v=-1;        dfs(1,0);        tot=tot-di+1;    }    printf("%d\n",tot);    return 0;}
0 0