bzoj1912 [Apio2010]patrol 巡逻

题目链接

找树的直径,我之前一只写的两次dfs,一次找最远点,第二次从最远点找最远点

这个题要“删”边,边有负权,于是只好DP了

Max1,Max2是从X往下最远和次远距离

son1,son2记录Max1,Max2是从那个儿子来的

 1 #include<algorithm>
 2 #include<iostream>
 3 #include<cstdlib>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<string>
 7 #include<cmath>
 8 #include<ctime>
 9 #include<queue>
10 #include<stack>
11 #include<map>
12 #include<set>
13 #define rre(i,r,l) for(int i=(r);i>=(l);i--)
14 #define re(i,l,r) for(int i=(l);i<=(r);i++)
15 #define Clear(a,b) memset(a,b,sizeof(a))
16 #define inout(x) printf("%d",(x))
17 #define douin(x) scanf("%lf",&x)
18 #define strin(x) scanf("%s",(x))
19 #define LLin(x) scanf("%lld",&x)
20 #define op operator
21 #define CSC main
22 typedef unsigned long long ULL;
23 typedef const int cint;
24 typedef long long LL;
25 using namespace std;
26 void inin(int &ret)
27 {
28     ret=0;int f=0;char ch=getchar();
29     while(ch<'0'||ch>'9'){if(ch=='-')f=1;ch=getchar();}
30     while(ch>='0'&&ch<='9')ret*=10,ret+=ch-'0',ch=getchar();
31     ret=f?-ret:ret;
32 }
33 int n,k,head[100010],next[200020],zhi[200020],ed=1,w[200020];
34 int son1[100010],son2[100010];
35 void add(int a,int b)
36 {
37     next[++ed]=head[a],head[a]=ed,zhi[ed]=b,w[ed]=1;
38     next[++ed]=head[b],head[b]=ed,zhi[ed]=a,w[ed]=1;
39 }
40 int o;
41 int dfs(int x,int fa,int &ans)
42 {
43     int Max1=0,Max2=0;
44     for(int i=head[x];i;i=next[i])if(zhi[i]!=fa)
45     {
46         int temp=w[i]+dfs(zhi[i],x,ans);
47         if(temp>Max1)Max2=Max1,Max1=temp,son2[x]=son1[x],son1[x]=i;
48         else if(temp>Max2)Max2=temp,son2[x]=i;
49     }
50     if(Max1+Max2>ans)ans=Max1+Max2,o=x;
51     return Max1;
52 }
53 int main()
54 {
55     inin(n),inin(k);
56     re(i,2,n)
57     {
58         int a,b;inin(a),inin(b);
59         add(a,b);
60     }
61     int zj1=0,zj2=0;
62     dfs(1,0,zj1);
63     if(k==1)
64     {
65         printf("%d",2*(n-1)-zj1+1);
66         return 0;
67     }
68     for(int i=son1[o];i;i=son1[zhi[i]])
69         w[i]=w[i^1]=-1;
70     for(int i=son2[o];i;i=son1[zhi[i]])
71         w[i]=w[i^1]=-1;
72     dfs(1,0,zj2);
73     printf("%d",2*(n-1)-zj1-zj2+2);
74      return 0;
75 }

 

posted @ 2016-03-16 10:32  HugeGun  阅读(146)  评论(0编辑  收藏  举报