Tree diameter POJ 1985 Cow Marathon

definition:

  Given a tree, the tree has a weight of each edge, the distance defined between two tree to the right of the path connecting the two points and edges. The diameter of the tree is called the distance between the farthest two nodes in the tree, the path connecting the two points is called the longest chain of the tree. The latter may also be referred to generally in diameter, i.e. the diameter value is a concept, a path may be on behalf of that


There are usually two diameters tree method for finding, are time complexity O (n). We assume the form of a directed graph tree given by N N-1 point edge strips and stored in the neighbor table.

Method a: DP tree

Advantages: 1 simple code

   2 may process the longest chain of each subtree rooted at the current point.

Disadvantages: easily determined diameter two endpoints.

Act II: twice DFS (BFS)

Advantages: easy to calculate the diameter of the particular node.

Disadvantages: can only seek diameter and distance.

 

Proved to not repeat them, it is relatively simple, there are also online.

The title fight is bare POJ 1985 Cow Marathon

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
#define R register
#define ll long long
inline ll read()
{
	ll aa=0;char cc=getchar();
	while(cc<'0'||cc>'9')cc=getchar();
	while(cc>='0'&&cc<='9')
		{aa=(aa<<3)+(aa<<1)+(cc^48);cc=getchar();}
	return aa;
}
const int N=1e6;
int tot,ver[N<<1],nxt[N<<1],edge[N<<1],first[N];
inline void add(int x,int y,int z)
{
	ver[++tot]=y;nxt[tot]=first[x];
	edge[tot]=z;first[x]=tot;return;
}
int n,f[N],ans;
void dp(int x,int fa)
{
	f[x]=0;
	for(R int i=first[x],v;i;i=nxt[i]){
		v=ver[i];if(v==fa)continue;
		dp(v,x);
		f[0]=max(f[0],f[x]+f[v]+edge[i]);
		f[x]=max(f[x],f[v]+edge[i]);
	}
}
int dis[N],pi,pj;
void dfs(int x,int fa)
{
	for(R int i=first[x],v;i;i=nxt[i]){
		v=ver[i];if(v==fa)continue;
		dis[v]=dis[x]+edge[i];dfs(v,x);
		if(dis[pj]<dis[v])pj=v;
	}
}
queue<int>qi;
void bfs(int x)
{
	memset(dis,-1,sizeof(dis));dis[x]=0;
	qi.push(x);
	while(!qi.empty()){
		int u=qi.front();qi.pop();
		for(R int i=first[u],v;i;i=nxt[i]){
			v=ver[i];if(dis[v]!=-1)continue;
			dis[v]=dis[u]+edge[i];qi.push(v);
			if(dis[v]>dis[pj])pj=v;
		}
	}
}
int main()
{
	n=read();read();
	for(R int i=1,x,y,z;i<n;++i){
		x=read();y=read();z=read();
		add(x,y,z);add(y,x,z);
	}
	f[0]=0;dp(1,1);ans=f[0];//dp
	
	dis[1]=0;pj=1;dfs(1,1);pi=pj;
	dis[pi]=0;dfs(pi,pi);ans=dis[pj];//dfs
	
	pj=1;bfs(1);pi=pj;
	bfs(pi);ans=dis[pj];//bfs
	
	printf("%d\n",ans);
}

 

Guess you like

Origin www.cnblogs.com/toot-wjh/p/11573183.html