Problem I
Roads in the North
Input: standard input
Output: standard output
Time Limit: 2 seconds
Memory Limit: 32 MB
Building and maintaining roads among communities in the far North is an expensive business. With this in mind, the roads are built in such a way 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
The input contains several sets of input. Each set of input 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. Two consecutive sets are separated by a blank line.
Output
For each set of input, you are to output a single line containing 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
题意:在一棵树上找距离最远的两个点。
思路:每个点找到它的子树中到叶节点距离最大的两个,答案就可能为这两个之和。
AC代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node
{
int v,w,next;
}edge[20010];
int Head[10010],num,dp[10010][2],maxn;
void add(int u,int v,int w)
{
edge[++num].v=v;
edge[num].w=w;
edge[num].next=Head[u];
Head[u]=num;
}
char s[110];
void dfs(int f,int u)
{
int j,v,w;
for(j=Head[u];j!=0;j=edge[j].next)
if(edge[j].v!=f)
{
v=edge[j].v;
dfs(u,v);
w=edge[j].w+dp[v][0];
if(w>dp[u][0])
{
dp[u][1]=dp[u][0];
dp[u][0]=w;
}
else if(w>dp[u][1])
dp[u][1]=w;
}
maxn=max(maxn,dp[u][0]+dp[u][1]);
}
int main()
{
int i,j,k,u,v,w;
while(gets(s))
{
if(s[0]=='\0')
{
dfs(0,1);
printf("%d\n",maxn);
memset(Head,0,sizeof(Head));
memset(dp,0,sizeof(dp));
maxn=0;num=0;
continue;
}
sscanf(s,"%d%d%d",&u,&v,&w);
add(u,v,w);
add(v,u,w);
}
dfs(0,1);
printf("%d\n",maxn);
}