我是靠谱客的博主 糟糕玉米,这篇文章主要介绍poj 1849 Two(树形dp求直径),现在分享给大家,希望可以做个参考。

树的直径:一棵树中两个点间的最长距离。

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

复制代码
1
2
3
4
5
5 2 1 2 1 2 3 2 3 4 2 4 5 1

Sample Output

复制代码
1
6

题意两个人从同一个点开始遍历整个树经过每条边的价值为这个边的价值求遍历完这个树的时候的最小价值。暴力走的话肯定是2*(权值和)表示每个边都经过了两次,要想让这个价值尽可能的小那就找一条主路从这个主路开始走这条路只走一遍不回头然后其他的边这样就能最小价值。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream> #include<string> #include <algorithm> #include <string.h> #include<cstdio> using namespace std; int ans=0,iv[1000050],v[1000050],ed[1000050],ne[10000000]; int f1[1000050],f2[1000050]; void add(int x,int y,int z){ ans++; ne[ans]=iv[x]; iv[x]=ans; v[ans]=y; ed[ans]=z; } int cnt=-1; void dfs(int x,int fa){ for(int i=iv[x];i;i=ne[i]){ int y=v[i]; if(y==fa) continue; dfs(y,x); if(f1[x]<f1[y]+ed[i]) { f2[x]=f1[x]; f1[x]=f1[y]+ed[i]; } else if(f2[x]<f1[y]+ed[i]) f2[x]=f1[y]+ed[i]; cnt=max(cnt,f1[x]+f2[x]); } } int main() { int n,s; while(cin>>n>>s){ memset(f1,0,sizeof(f1)); memset(f2,0,sizeof(f2)); cnt=ans=0; int cm=0; for(int i=1;i<n;i++){ int x,y,z; cin>>x>>y>>z; add(x,y,z); add(y,x,z); cm+=2*z; } dfs(s,-1); cout<<cm-cnt<<endl; } }

 

最后

以上就是糟糕玉米最近收集整理的关于poj 1849 Two(树形dp求直径)的全部内容,更多相关poj内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(51)

评论列表共有 0 条评论

立即
投稿
返回
顶部