旅行商问题(dfs)

链接:https://ac.nowcoder.com/acm/contest/547/E
来源:牛客网
 

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld

题目描述

旅行商来到了一个新的国家,这个国家有N个城市,他们直接由N-1条道路相连接,每条道路的长度不尽相同

旅行商现在在1号城市,若他要每一个城市都游览一遍,他需要行走的最短路程是多少?

输入描述:

第一行一个数N (50000>N>1)

代表城市个数

之后N-1行

每行三个数x y z

代表从x到y的距离为z

输出描述:

输出最小距离

示例1

输入

复制

3
1 2 1
1 3 1

输出

复制

3

这道题的变形在于要从1走到其余任意一点,所以就会出现重复的想象,那就应该尽可能少重复,或者重复小的哪个部分。首先定义一个结构体vector对数数字进行处理。然后就使用搜索来做。

代码如下:

int n;
vector<node>ve[maxn];
int vis[maxn];
ll ans = 0;
void dfs(int a, int sum){
	vis[a] = 1;
	int len = ve[a].size();
	if(len == 1 && vis[ve[a][0].v]){
		ans = max(ans, sum);
		return ;
	}
	for(int i = 0; i < len; i++){
		if(!vis[ve[a][i].v]){
			dfs(ve[a][i].v, sum + ve[a][i].val);
		}
	}
}
int main(){
	ios::sync_with_stdio(false);
	cin >> n;
	int x, y, z;
	ll sum = 0;
	for(int i = 1; i < n; i++){
		cin >> x >> y >> z;
		ve[x].push_back(node{y, z});
		ve[y].push_back(node{x, z});
		sum += z;
	}
	memset(vis, 0, sizeof(vis));
	dfs(1, 0);
	cout << sum*2-ans << endl;
	return 0;
}

好好学基础知识。

猜你喜欢

转载自blog.csdn.net/ab1605014317/article/details/88604561