树的直径poj1985

树的直径:

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

先从任意一顶点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;
}

  

猜你喜欢

转载自www.cnblogs.com/starve/p/10817234.html