Problem Description
In the battlefield , an effective way to defeat enemies is to break their communication system.
The information department told you that there are n enemy soldiers and their network which have n-1 communication routes can cover all of their soldiers. Information can exchange between any two soldiers by the communication routes. The number 1 soldier is the total commander and other soldiers who have only one neighbour is the frontline soldier.
Your boss zzn ordered you to cut off some routes to make any frontline soldiers in the network cannot reflect the information they collect from the battlefield to the total commander( number 1 soldier).
There is a kind of device who can choose some routes to cut off . But the cost (w) of any route you choose to cut off can’t be more than the device’s upper limit power. And the sum of the cost can’t be more than the device’s life m.
Now please minimize the upper limit power of your device to finish your task.
Input
The input consists of several test cases.
The first line of each test case contains 2 integers: n(n<=1000)m(m<=1000000).
Each of the following N-1 lines is of the form:
ai bi wi
It means there’s one route from ai to bi(undirected) and it takes wi cost to cut off the route with the device.
(1<=ai,bi<=n,1<=wi<=1000)
The input ends with n=m=0.
Output
Each case should output one integer, the minimal possible upper limit power of your device to finish your task.
If there is no way to finish the task, output -1.
Sample Input
5 5
1 3 2
1 4 3
3 5 5
4 2 6
0 0
Sample Output
3
解题报告
题意是让我们找一个lim,使得我们能够找到一种方案,在切断的边权和在lim以内的情况下能够保证叶子节点与根节点不连通。
我们定义dp[u]表示让以u为根的子树中所有叶子节点不与根连同的最小代价。
考虑转移。对于一条边u->v,我们考虑怎样将v的子树同u的其他子树合并。如果我们切断这条边,显然u的子树一定不与根相连。同样我们也可以继承雨来的dp[v]值。
那么转移方程就是dp[u]+=min(ed[i].w,dp[v])(ed[i].w<=lim)。
叶子节点的初值赋题目给的最值(Hawo11教导我们,要赋inf的话需要一些特殊的技巧)。
代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1000,M=1000000;
struct edge
{
int v,w,next;
}ed[N*2+5];
int n,m;
int head[N+5],num;
int dp[N+5];
int vmax;
void build(int u,int v,int w)
{
ed[++num].v=v;
ed[num].w=w;
ed[num].next=head[u];
head[u]=num;
}
void dfs(int u,int f,int lim)
{
int flag=0;
dp[u]=0;
for(int i=head[u];i!=-1;i=ed[i].next)
{
int v=ed[i].v;
if(v==f)continue;
flag=1;
dfs(v,u,lim);
if(ed[i].w<=lim)dp[u]+=min(dp[v],ed[i].w);
else dp[u]+=dp[v];
}
if(!flag)dp[u]=M+5;
}
bool check(int mid)
{
dfs(1,0,mid);
return dp[1]<=m;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
if(!n&&!m)break;
memset(head,-1,sizeof(head));num=0;
vmax=0;
for(int i=1;i<=n-1;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
build(u,v,w);
build(v,u,w);
vmax=max(vmax,w);
}
int lf=1,rg=vmax,ans=-1;
while(lf<=rg)
{
int mid=(lf+rg)>>1;
if(check(mid))ans=mid,rg=mid-1;
else lf=mid+1;
}
printf("%d\n",ans);
}
return 0;
}