【POJ】[2631]Roads in the North

文章字数:130

问题描述

Roads in the North

问题分析

运用DFS求树的直径

 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
#include<stdio.h>
#include<string.h>
int head[10200];
int headcnt;
int max,t;
struct List {
	int u,v,w;
	int next;
} edge[10200];
void add(int u,int v,int w) {
	edge[headcnt].u=u;
	edge[headcnt].v=v;
	edge[headcnt].w=w;
	edge[headcnt].next=head[u];
	head[u]=headcnt++;
}
void dfs(int u,int v,int w) {
	if(max<w)
		max=w,t=u;
	for(int i=head[u]; i!=-1; i=edge[i].next) {
		if(edge[i].v!=v)
			dfs(edge[i].v,u,w+edge[i].w);
		}
}
int main() {
	headcnt=0;
	memset(head,-1,sizeof(head));
	int u,v,w;
	while(scanf("%d %d %d",&u,&v,&w)!=EOF) {
		add(u,v,w);
		add(v,u,w);
	}
	max=0;
	dfs(1,0,0);
	dfs(t,0,0);
	printf("%d\n",max);
	return 0;
}

加载中...