剑指offer: [POJ]2631 The Fair Nut and the Best Path 树形DP的方式求解树的直径

题目大意: 树上有村子,求最远两个村子的距离

解题思路:很显然这是一个裸的树的直径,有很多种方法可以求解,这些写一下树形DP的解法
首先定义一个F数组,f[x]的含义是以x点为根节点,到最远的子树叶子点距离,然后每个点都跑一遍即可。

Code:

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=10010;

struct node {
	int v,w;
	node() {};
	node(int V,int W) { v=V;w=W; };
};
 
int f[N],ans;           //f[x] x点到最远的点距离 
vector <node> G[N];
 
void dfs(int u,int fa) {
	for(int i=0,v,w;i<G[u].size();i++){  
		v=G[u][i].v,w=G[u][i].w;
		if(v==fa) continue;
		dfs(v,u);
		ans=max(ans,f[u]+f[v]+w);   //状态转移之前求一个最大值
		f[u]=max(f[u],f[v]+w);     //更新一下f[u],以便于回溯的时候更新他的父亲节点
	}
}
int main() {
	int i,j,k;
	while(cin>>i>>j>>k) {
		G[i].push_back(node(j,k));
		G[j].push_back(node(i,k));
	}
	dfs(1,0);
	cout<<ans;
}

猜你喜欢

转载自blog.csdn.net/weixin_43872264/article/details/107890111