Center tree tree DP-

Center tree

Given a tree, the tree includes n nodes (numbered 1 ~ n) and the n-1 undirected edges, each edge has a weight.

Please find a point in the tree so that the tree points to other nodes most distant lately.

Input format
The first line contains the integer n.

Next, n-1 rows, each row containing three integers ai, BI, ci, ci represents a weight of the presence of an edge between points ai and bi.

Output format
output an integer, representing the tree to find the most distant point of the other nodes.

Data range
1≤n≤10000,
1≤ai, bi≤n,
-105≤ci≤105
input sample:
. 5
2. 1. 1
. 3. 1 2
. 4. 3. 1
. 5. 1. 1
Output Sample:
2

answer:

This question needs to let the largest minimum requirements tree in the center of our first tree as a circle in the center is not only when we are able to guarantee a minimum distance. So the center of our trees is such a reason. We want to find a point from the root top and bottom of the longest distance the longest distance, and then take a small value of these two. So we need twice the tree DP. Once up and once down. For we can only leaf node upwards. What is somewhat similar to the previous question and the place is it? Process up in when we have this node down to us from the same level of root node in the same distance down the biggest. So we can choose another second large distances (as to ensure maximum minimum), but if we are not this node, then we can only go to the node that contains the maximum distance (as to ensure maximum).

#include<bits/stdc++.h>
using namespace std;
const int N=2e4+7,inf=0x3f3f3f3f;
int ne[N],h[N],w[N],e[N],cnt,d1[N],d2[N],r1[N],r2[N],up[N];
bool lef[N];
void add(int a,int b,int c)
{
	e[cnt]=b,w[cnt]=c,ne[cnt]=h[a],h[a]=cnt++;
}
int dfs_d(int u,int f)
{
	d1[u]=d2[u]=-inf;
	for(int i=h[u];i!=-1;i=ne[i]){
		int j=e[i];
		if(j==f) continue;
		int d=dfs_d(j,u)+w[i];
		if(d>=d1[u]){
			d2[u]=d1[u]; d1[u]=d;
			r2[u]=r1[u]; r1[u]=j;
		}else if(d>=d2[u]) d2[u]=d,r2[u]=j;
	}
	if(d1[u]==-inf){
		d1[u]=d2[u]=0;
		lef[u]=1;
	}
	return d1[u];
}
int dfs_u(int u,int f)
{
	for(int i=h[u];i!=-1;i=ne[i]){
		int j=e[i];
		if(j==f) continue;
		if(r1[u]==j) up[j]=max(up[u],d2[u])+w[i];
		else up[j]=max(up[u],d1[u])+w[i];
		dfs_u(j,u);
	}
}
int main()
{
	int n; cin>>n;
	memset(h,-1,sizeof h);
	for(int i=1;i<n;i++){
		int a,b,c; cin>>a>>b>>c;
		add(a,b,c),add(b,a,c);
	}
	dfs_d(1,-1);
	dfs_u(1,-1);
	int res=d1[1];
	for(int i=2;i<=n;i++){
		if(lef[i]) res=min(res,up[i]);
		else res=min(res,max(d1[i],up[i]));
	} 
	cout<<res<<endl;
}
发布了76 篇原创文章 · 获赞 4 · 访问量 681

Guess you like

Origin blog.csdn.net/weixin_42979819/article/details/103944969