POJ1849Two[DP|树的直径](扩展HDU4003待办)

Two
Time Limit: 1000MS   Memory Limit: 30000K
Total Submissions: 1390   Accepted: 701

Description

The city consists of intersections and streets that connect them.

Heavy snow covered the city so the mayor Milan gave to the winter-service a list of streets that have to be cleaned of snow. These streets are chosen such that the number of streets is as small as possible but still every two intersections to be connected i.e. between every two intersections there will be exactly one path. The winter service consists of two snow plovers and two drivers, Mirko and Slavko, and their starting position is on one of the intersections.

The snow plover burns one liter of fuel per meter (even if it is driving through a street that has already been cleared of snow) and it has to clean all streets from the list in such order so the total fuel spent is minimal. When all the streets are cleared of snow, the snow plovers are parked on the last intersection they visited. Mirko and Slavko don’t have to finish their plowing on the same intersection.

Write a program that calculates the total amount of fuel that the snow plovers will spend.

Input

The first line of the input contains two integers: N and S, 1 <= N <= 100000, 1 <= S <= N. N is the total number of intersections; S is ordinal number of the snow plovers starting intersection. Intersections are marked with numbers 1...N.

Each of the next N-1 lines contains three integers: A, B and C, meaning that intersections A and B are directly connected by a street and that street's length is C meters, 1 <= C <= 1000.

Output

Write to the output the minimal amount of fuel needed to clean all streets. 

Sample Input

5 2
1 2 1
2 3 2
3 4 2
4 5 1

Sample Output

6

Source

DP也可以,f[i]和g[i]分别处理两个人子树i进去回来和只进不回,f[i]=sum{w of i's son}*2,g[i]两种情况,两人进入i的同一个或不同一个孩子,好麻烦啊

其实答案就是sum{w}*2-w直径,无论从哪里开始都可以

证明:

虽然s是起点(很多人的起点就忽略了这个),

s在直径上好说,

假设s不再直径上,我们选择直径某点为root,从s到root到话费也是w*2,和从root开始一个到s又回来是一样的,然后就和上面一样了

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=1e5+;
int n,s,u,v,w,sum=,mx=;
struct edge{
int v,ne,w;
}e[N*];
int h[N],cnt=;
inline void ins(int u,int v,int w){
cnt++;
e[cnt].ne=h[u];e[cnt].v=v;e[cnt].w=w;h[u]=cnt;
cnt++;
e[cnt].ne=h[v];e[cnt].v=u;e[cnt].w=w;h[v]=cnt;
}
int f[N][];
int dp(int u,int fa){
int &t0=f[u][],&t1=f[u][];
if(t0!=-) return t0;
t0=;
for(int i=h[u];i;i=e[i].ne){
int v=e[i].v;
if(v==fa) continue;
int d=dp(v,u)+e[i].w;
if(d>t0) t1=t0,t0=d;
else if(d>t1) t1=d;
}
return t0;
}
int main(int argc, const char * argv[]) {
scanf("%d%d",&n,&s);
for(int i=;i<=n-;i++){
scanf("%d%d%d",&u,&v,&w);
ins(u,v,w);sum+=w*;
}
memset(f,-,sizeof(f));
dp(,-);
for(int i=;i<=n;i++)
mx=max(mx,f[i][]+f[i][]);
cout<<sum-mx;
//printf("\n\n%d %d",sum,mx);
return ;
}

扩展:2-->k

HDU4003(HDU最近挂了)

和选课很像了,这里特殊之处是d[i][0]的含义是一个下去又上来,其他的下去不上来

以后做做吧

上一篇:Alice and Bob


下一篇:HighCharts之2D堆柱状图