标签:segment sscanf while void one ted find only you
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 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.
You are to output a single integer: the road distance between the two most remote villages in the area.
5 1 6
1 4 5
6 3 9
2 6 8
6 1 7
22
树的结点往上长型dp
Note:
#include<bits/stdc++.h>
using namespace std;
int dp1[10001],dp2[10001],head[10001];
int cnt=0,maxi=0;
struct edge{int v,w,next;}Edge[20001];
inline void add_edge(int u,int v,int w){
Edge[++cnt]={v,w,head[u]};head[u]=cnt;
}
void dfs(int s,int pre){
for(int i=head[s];i;i=Edge[i].next){
int v=Edge[i].v;
if(v==pre)continue;dfs(v,s);
if(dp1[v]+Edge[i].w>dp1[s])dp2[s]=dp1[s],dp1[s]=dp1[v]+Edge[i].w;
else if(dp1[v]+Edge[i].w>dp2[s])dp2[s]=dp1[v]+Edge[i].w;
}maxi=max(maxi,dp1[s]+dp2[s]);
}
int main(){
int a,b,c,flag;char m[20];
while(1){
memset(head,-1,sizeof(head));memset(dp1,0,sizeof(dp1));
flag=cnt=maxi=0;memset(dp2,0,sizeof(dp2));
while(gets(m)!=NULL&&m[0]!='\0'){
sscanf(m,"%d%d%d",&a,&b,&c);
add_edge(a,b,c),add_edge(b,a,c);flag=1;
}
if(flag==1){
dfs(1,0);
printf("%d\n",maxi);
}if(m[0]!='\0')break;
}
return 0;
}
UVA10308 Roads in the North 树的最长路径
标签:segment sscanf while void one ted find only you
原文地址:https://www.cnblogs.com/chanceYu/p/12250031.html