POJ 2631 Roads in the North

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_42369449/article/details/82809646

 算法:树的直径裸题

难度:*NOIP-*

没有什么好说的,跑2遍dfs,找到树的直径即可!

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#define ll long long
#define N 10005 
using namespace std;
struct node
{
	int next;
	int to;
	int val;
}edge[N<<1];
int head[N],vis[N],dis[N];
int cnt=1;
void init()
{
	cnt=1;
	memset(head,-1,sizeof(head));
}
void add(int u,int v,int w)
{
	edge[cnt].next=head[u];
	edge[cnt].to=v;
	edge[cnt].val=w;
	head[u]=cnt++;
}
int ans;
int yy;
void dfs(int rt,int d)
{
	for(int i = head[rt];i != -1;i = edge[i].next)
	{
		int to=edge[i].to;
		if(!vis[to])
		{
			vis[to]=1;
			dis[to]=d+edge[i].val;
			if(dis[to]>ans)
			{
				ans=dis[to];
				yy=to;
			}
			dfs(to,dis[to]);
		}
	}
}
int main()
{
	int x,y,w;
	init();
	while(scanf("%d%d%d",&x,&y,&w)!=EOF)
	{
		add(x,y,w);
		add(y,x,w);
	}
	vis[1]=1;
	dfs(1,0);
	memset(vis,0,sizeof(vis));
	vis[yy]=1;
	dfs(yy,0);
	printf("%d\n",ans);
	return 0 ;
}

猜你喜欢

转载自blog.csdn.net/qq_42369449/article/details/82809646
今日推荐