7 2
6 7
3 4
6 5
1 2
3 2
4 5
2
思路:
我们可以二分该最小值,然后验证其是否合法,即保证最长链长度不可大于二分的答案
我们设dp[i]表示以第ii个节点为根的子树中,合法的最长链两端点路径不跨过根节点的链的长度
然后我们就可以用dp【i】计算要砍去多少条边,从而判断当前二分出的答案的合法性
虽然感觉很简单,但一细想发现转移并不是那么好打
显然直接求max(f[son])是不可行的,因为这不保证合法,但我们想,当我们选出两条儿子所在的最长链两端点路径不跨过根节点的链,发现当他们接在一起时长度过大,需要从中砍断的时候,会发现只有两种情况
把最长链链顶的边给砍了最优(如果砍的不是链顶的边,或者砍了较短的链,那就有可能还有其他不合法的情况,还要再砍一次)
砍了之后,不会对其父节点造成影响(由于砍完之后,这两个点都不在一个连通块里,固然不会有影响)。
至此这个题目基本上就可以秒切了,只要将当前点的所有dp【son】从大到小排个序,依次判断相邻的两个最长链两端点路径不跨过根节点的链是否合法,若合法就可以吧dp【i】赋值,否则就继续找,然后砍的数目加一。
代码:
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn=1e6+10; 4 struct node 5 { 6 int to; 7 int next; 8 }way[maxn]; 9 int head[maxn]; 10 int tot=0; 11 int fa[maxn]; 12 int top,sumn; 13 int x,y,s,n; 14 int a[maxn]; 15 int add(int x,int y) 16 { 17 way[++tot].next=head[x]; 18 way[tot].to=y; 19 head[x]=tot; 20 } 21 int dfs(int x,int f,int cut) 22 { 23 fa[x]=0; 24 for(int i=head[x];i;i=way[i].next) 25 { 26 if(way[i].to!=f) 27 { 28 dfs(way[i].to,x,cut); 29 } 30 } 31 top=0; 32 for(int i=head[x];i;i=way[i].next) 33 { 34 if(way[i].to!=f) 35 { 36 a[++top]=fa[way[i].to]+1; 37 } 38 } 39 sort(a+1,a+1+top); 40 while(top&&a[top]+a[top-1]>cut) 41 { 42 top--; 43 sumn++; 44 } 45 fa[x]=a[top]; 46 } 47 int check(int x) 48 { 49 sumn=0; 50 dfs(1,0,x); 51 return sumn<=s; 52 } 53 int main() 54 { 55 cin>>n>>s; 56 for(int i=1;i<=n-1;i++) 57 { 58 cin>>x>>y; 59 add(x,y); 60 add(y,x); 61 } 62 63 int l=0; 64 int r=n; 65 while(l<r) 66 { 67 int mid=(l+r)>>1; 68 if(check(mid)) 69 { 70 r=mid; 71 } 72 else 73 { 74 l=mid+1; 75 } 76 } 77 cout<<l<<endl; 78 return 0; 79 }
问题 C: 「Usaco2010 Dec」奶牛健美操O(∩_∩)O
原文:https://www.cnblogs.com/2529102757ab/p/11681390.html