[蓝桥杯 2013 省 A] 大臣的旅费(dfs)

        通过题目描述我们可以清楚,如果要找到最大消费,我们就需要找到最长的边,而对于最长的边,我们需要进行dfs,从王国出发,开始寻找最长边,最后寻找到最长边进行高斯求和即可

上代码

#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<unordered_map>

using namespace std;

struct Node{
	int value;
	vector <Node*> children;//存储子节点 
	vector <int> length;//存储路径长度 
};
int n;
unordered_map <int,Node*> mp;
bool *st;
int res;

int dfs(int x, int fa)//分别表示访问到了哪个结点,父节点 
{
	int dist = 0;//返回最长链 
	int d1 = 0, d2 = 0;//返回最长链和次长链 
	for(int i = 0; i < mp[x]->children.size(); i++){
		Node* node1 = mp[x]->children[i];
		if(node1->value == fa) continue;//如果当前子节点是父节点,直接跳过
		int d = dfs(node1->value, x) + mp[x]->length[i];//当前节点最长就是其子节点中最长的数值
		if(d > d1){//如果当前链长大于最长链长,就分别更新最长链长和次长链 
			d2 = d1;
			d1 = d;
		}
		else if(d > d2) d2 = d;//如果只大于次长链就只更新次长链
		dist = max(dist, d);//当前最长链 
	}
	res = max(res, d1 + d2); 
	return dist;
}

int main(void)
{
	cin >> n;
	Node node[n + 10];
	st = new bool[n + 10];
	memset(st, 0, sizeof(st));
	for(int i = 1; i <= n; i++){
		node[i].value = i;
		mp[i] = &node[i];
	} 
	
	for(int i = 1; i <= n - 1; i++){
		int x, y, z; cin >> x >> y >> z;
		mp[x]->children.push_back(mp[y]);
		mp[y]->children.push_back(mp[x]);
		mp[x]->length.push_back(z);
		mp[y]->length.push_back(z);
	}
	
	dfs(1, -1);
	
	cout << 10 * res + (res + 1) * res / 2 << endl;
	
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值