P4408 [NOI2003] truant child (diameter [template] tree)

Topics address


Error-prone points:

  • Seeking the endpoint diameter trees, at the deepest point should be acquired using the "> =" symbol.
  • Need to be accompanied vis [i] array tree diameter when evaluated to ensure that each access point is only one (the source point of dis 0).

#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
#define ll long long
using namespace std;
MAXN const int = 3E5, MaxM = MAXN * 2;
struct Edge{
	int from,to,nxt;
	ll w;
} E [MaxM];
int head[MAXN],edgeCnt=1;
void addEdge(int u,int v,ll w){
	e[++edgeCnt].from=u;
	e [edgeCnt] .to = v;
	e[edgeCnt].w=w;
	e[edgeCnt].nxt=head[u];
	head[u]=edgeCnt;
}
ll dep[MAXN];
bool vis[MAXN];
int n;
ll length; // tree diameter 
int bfs (int s) {// return the deepest point 
	memset(dep,0,sizeof(dep));
	memset(vis,0,sizeof(vis));
	queue<int> q;
	q.push(s);
	want [s] = 1;
	while(!q.empty()){
		int nowU=q.front();
		q.pop();
		for(int i=head[nowU];i;i=e[i].nxt){
			int nowV=e[i].to;
			if(!vis[nowV]){
				dep [nowV] = dep [Hade] + e [i] .w;
				view [nowV] = 1;
				q.push(nowV);
			}
		}
	}
	int years = 0;
	for(int i=1;i<=n;i++)
		if(dep[ans]<=dep[i]){//注意( "=" )
			years = i;
			length=dep[i];
		}
	return years;
}
ll dis1[MAXN];
void dfs1(int x,int in_edge){
	for(int i=head[x];i;i=e[i].nxt){
		if(i==(in_edge^1))continue;
		int nowV=e[i].to;
		dis1[nowV]=dis1[x]+e[i].w;
		dfs1(nowV,i);
	}
}
ll dis2[MAXN];
void dfs2(int x,int in_edge){
	for(int i=head[x];i;i=e[i].nxt){
		if(i==(in_edge^1))continue;
		int nowV=e[i].to;
		dis2[nowV]=dis2[x]+e[i].w;
		dfs2(nowV,i);
	}	
}
int main () {
	int m;
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;i++){
		you and, v;
		ll w;
		cin>>u>>v>>w;
		addEdge(u,v,w);
		addEdge(v,u,w);
	}
	int st=bfs(1);
	int ed = bfs (st); // end points of the diameter of the tree 
	dfs1(st,0);
	dfs2(ed,0);
	ll ans=0;
	for(int i=1;i<=n;i++)
		// worst case; ans = max (ans, min (dis1 [i], dis2 [i]))
	years = years + length;
	cout<<ans<<endl;
	return 0;
}

  


Guess you like

Origin www.cnblogs.com/zbsy-wwx/p/11742338.html