原题:
Roads in the North
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 5309 Accepted: 2508
Description
Building and maintaining roads among communities in the far North is an expensive business. With this in mind, the roads are build such that there is only one route from a village to a village that does not pass through some other village twice.
Given is an area in the far North comprising a number of villages and roads among them such that any village can be reached by road from any other village. Your job is to find the road distance between the two most remote villages in the area.
The area has up to 10,000 villages connected by road segments. The villages are numbered from 1.
Input
Input to the problem is a sequence of lines, each containing three positive integers: the number of a village, the number of a different village, and the length of the road segment connecting the villages in kilometers. All road segments are two-way.
Output
You are to output a single integer: the road distance between the two most remote villages in the area.
Sample Input
5 1 6
1 4 5
6 3 9
2 6 8
6 1 7
Sample Output
22
Source
The UofA Local 1999.10.16
中文:
给你一棵树,让你找这个树上的直径(树上距离最远的两个节点)
数据输入方式为输入多行,每一行有三个数,分别表示相连的两个节点和边的权值。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
const int N=10005;
vector<int> G[N];
map<pair<int,int>,int> mp;
int f1[N],f2[N];
int ans;
void dp(int x,int fa)
{
for(int i=0;i<G[x].size();i++)
{
if(G[x][i]==fa)
continue;
dp(G[x][i],x);
int w = mp[make_pair(x,G[x][i])];
if(f1[x]<f1[G[x][i]]+w)
{
f2[x]=f1[x];
f1[x]=f1[G[x][i]]+w;
}
else
{
if(f2[x]<f1[G[x][i]]+w)
f2[x]=f1[G[x][i]]+w;
}
ans=max(ans,f1[x]+f2[x]);
}
}
int main()
{
//ios::sync_with_stdio(false);
int a,b,c;
memset(f1,0,sizeof(f1));
memset(f2,0,sizeof(f2));
mp.clear();
/*
int n,m;
cin>>n>>m;
for(int i=1;i<=m;i++)
{
cin>>a>>b>>c;
G[a].push_back(b);
G[b].push_back(a);
mp[make_pair(a,b)]=c;
mp[make_pair(b,a)]=c;
}
ans=-1;
dp(1,0);
cout<<ans<<endl;
*/
while(scanf("%d %d %d",&a,&b,&c)!=EOF)
{
G[a].push_back(b);
G[b].push_back(a);
mp[make_pair(a,b)]=c;
mp[make_pair(b,a)]=c;
}
ans=0;
dp(1,0);
printf("%d\n",ans);
memset(f1,0,sizeof(f1));
memset(f2,0,sizeof(f2));
mp.clear();
return 0;
}
解答:
简单的计算树的直径的裸题,代码中使用动态规划的方法计算。
设置两个数组f1[x]与f2[x],记录记录节点x以及其子树所得到的最长距离和次长距离(第二长)。
转移方程为遍历到节点x时,更新最长距离f1[x]和次长距离f2[x],x的某一个子节点为G[x][i],x与G[x][i]之间的权值为w,那么
如果
f
1
[
x
]
<
f
1
[
G
[
x
]
[
i
]
]
+
w
f1[x]<f1[G[x][i]]+w
f1[x]<f1[G[x][i]]+w
则
f
2
[
x
]
=
f
1
[
x
]
;
f2[x]=f1[x];
f2[x]=f1[x];
f
1
[
x
]
=
f
1
[
G
[
x
]
[
i
]
]
+
w
f1[x]=f1[G[x][i]]+w
f1[x]=f1[G[x][i]]+w
否则,如果
f
2
[
x
]
<
f
1
[
G
[
x
]
[
i
]
]
+
w
f2[x]<f1[G[x][i]]+w
f2[x]<f1[G[x][i]]+w
则
f
2
[
x
]
=
f
1
[
G
[
x
]
[
i
]
]
+
w
f2[x]=f1[G[x][i]]+w
f2[x]=f1[G[x][i]]+w
那么得到经过当前节点x的最远两点距离就是f1[x]+f2[x]
从叶子节点开始计算,计算至根节点,每次更新计算的最远两点距离即可。