码迷,mamicode.com
首页 > 其他好文 > 详细

树的直径poj1985

时间:2019-05-06 01:14:21      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:string   for   scan   ext   class   %s   front   cst   之间   

树的直径:

利用了树的直径的一个性质:距某个点最远的叶子节点一定是树的某一条直径的端点。

先从任意一顶点a出发,bfs找到离它最远的一个叶子顶点b,然后再从b出发bfs找到离b最远的顶点c,那么b和c之间的距离就是树的直径。

用dfs也可以。

http://poj.org/problem?id=1985

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
inline int read(){
	int sum=0,x=1;
	char ch=getchar();
	while(ch<‘0‘||ch>‘9‘){
		if(ch==‘-‘)
			x=0;
		ch=getchar();
	}
	while(ch>=‘0‘&&ch<=‘9‘)
		sum=(sum<<1)+(sum<<3)+(ch^48),ch=getchar();
	return x?sum:-sum;
}
inline void write(int x){
	if(x<0)
		putchar(‘-‘),x=-x;
	if(x>9)
		write(x/10);
	putchar(x%10+‘0‘);
}
const int M=4e4+4;
struct node{
	int v,w,nextt;
}e[M<<1];
int head[M],book[M],dis[M],n,flag,maxx,tot,b;
void bfs(int s){
	if(!flag)
		flag=1;
	else{
		for(int i=0;i<=n;i++)
			book[i]=0,dis[i]=0;
	}
	book[s]=1;
	queue<int>que;
	que.push(s);
	b=s;
	maxx=0;
	while(!que.empty()){
		int u=que.front();
		que.pop();
		for(int i=head[u];~i;i=e[i].nextt){
			int v=e[i].v;
			if(!book[v]){
				book[v]=1;
				que.push(v);
				dis[v]=dis[u]+e[i].w;
				if(dis[v]>maxx){
					maxx=dis[v];
					b=v;
				}
			}
		}
	}
}
void addedge(int u,int v,int w){
	e[tot].v=v;
	e[tot].w=w;
	e[tot].nextt=head[u];
	head[u]=tot++;
}
char s[2];
int main(){
	int m;
	n=read(),m=read();
	for(int i=0;i<=n;i++)
		head[i]=-1;
	while(m--){
		int u=read(),v=read(),w=read();
		scanf("%s",s);
		addedge(u,v,w);
		addedge(v,u,w);
	}
	bfs(1);
	bfs(b);
	write(maxx);
	putchar(‘\n‘);
	return 0;
}

  

树的直径poj1985

标签:string   for   scan   ext   class   %s   front   cst   之间   

原文地址:https://www.cnblogs.com/starve/p/10817234.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!