[Apio2010]patrol 巡逻

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=1显然,找1引出的最长链,将它们连起来即可。

那么K=2呢?同样找链,不过之前连了边的两条链,如果再和其他链连起来会怎样???你会发现,本来只要走一次,又变成了走两次。因此,我们可以先做完K=1的情况,将那两条链的点的权值全部改为-1,然后再找两条最长链连起来即可。

/*program from Wolfycz*/
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define inf 0x7f7f7f7f
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
inline int read(){
    int x=0,f=1;char ch=getchar();
    for (;ch<'0'||ch>'9';ch=getchar())  if (ch=='-')    f=-1;
    for (;ch>='0'&&ch<='9';ch=getchar())    x=(x<<1)+(x<<3)+ch-'0';
    return x*f;
}
inline void print(int x){
    if (x>=10)  print(x/10);
    putchar(x%10+'0');
}
const int N=1e5;
int pre[(N<<1)+10],now[N+10],child[(N<<1)+10],val[(N<<1)+10];
int F_Dn[N+10],G_Dn[N+10];
int n,K,Len,ID,tot=1;
void join(int x,int y,int z){pre[++tot]=now[x],now[x]=tot,child[tot]=y,val[tot]=z;}
void insert(int x,int y,int z){join(x,y,z),join(y,x,z);}
int dfs(int x,int fa){
    int F=0,G=0;
    for (int p=now[x],son=child[p];p;p=pre[p],son=child[p]){
        if (son==fa)    continue;
        int Len=dfs(son,x)+val[p];
        if (Len>F)  G=F,G_Dn[x]=F_Dn[x],F=Len,F_Dn[x]=p;
        else    if (Len>G)  G=Len,G_Dn[x]=p;
    }
    if (Len<F+G)    Len=F+G,ID=x;
    return F;
}
int main(){
    n=read(),K=read();
    for (int i=1;i<n;i++){
        int x=read(),y=read();
        insert(x,y,1);
    }
    int Ans=(n-1)<<1;
    dfs(1,0);
    Ans-=Len-1;
    if (K==2){
        for (int p=F_Dn[ID];p;p=F_Dn[child[p]]) val[p]=val[p^1]=-1;
        for (int p=G_Dn[ID];p;p=F_Dn[child[p]]) val[p]=val[p^1]=-1;
        Len=0,dfs(1,0);
        Ans-=Len-1;
    }
    printf("%d\n",Ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Wolfycz/p/9745863.html