[toj3517]【求树的直径】

本文介绍了一种求解树中任意两点间最大距离的算法——树的直径算法,并提供了使用迪杰斯特拉算法的具体实现,包括核心代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意是给一棵树,求树中任意两点间的距离的最大值。其本质就是:求树的直径。

最短路径部分,可以用迪杰斯特拉实现。可以加优先队列优化一下,但是这里数据不大可以随便搞,快速读入并没有时间优化效果。

 

14932282015-01-02 13:37:59Accepted3517C++1.7K0'00.11"980K

 

0'00.11"980K

 

#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <utility>
#include <queue>
using namespace std;

const int MAX = 2048;
struct Edge {
	int to;
	int len;
};
vector<Edge> G[MAX];
bool vis[MAX];
int mincost[MAX];
const int INF = 0xfffffff;
int n;

//求from到其它所有点的距离(最短路)中的最大值和距离最大的点 
pair<int, int> djistra(int from) {
	fill(mincost, mincost + n + 1, INF);
	memset(vis, false, sizeof(vis));
	mincost[from] = 0;
	pair<int, int> ans = make_pair(from, 0);
	while (true) {
		int v = -1;
		for (int u = 1; u <= n; ++u) {
			if (!vis[u] && (v == -1 || mincost[u] < mincost[v])) {
				v = u;
			}
		}
		if (v == -1) break;
		vis[v] = true;
		if (ans.second < mincost[v]) {
			ans.first = v;
			ans.second = mincost[v];
		}
		for (int u = 0; u < G[v].size(); ++u) {
			if (mincost[G[v][u].to] > mincost[v] + G[v][u].len) {
				mincost[G[v][u].to] = mincost[v] + G[v][u].len;
			}
		}
	}//while
	return ans;
}

inline int read() {
	char ch;
	while ((ch = getchar()) < '0' || ch > '9');
	int x = ch - '0';
	while ((ch = getchar()) >= '0' && ch <= '9') {
		x = (x << 3) + (x << 1) + ch - '0';
	}
	return x;
}

int main() {
	int T;
	T = read();
	//scanf(" %d", &T);
	while (T--) {
		n = read();
		//scanf(" %d", &n);
		for (int i = 1; i <= n; ++i) G[i].clear();
		int s, t, c;
		for (int i = 1; i < n; ++i) {
			s = read();
			t = read();
			c = read();
			//scanf(" %d %d %d", &s, &t, &c);
			G[s].push_back((struct Edge){t, c});
			G[t].push_back((struct Edge){s, c});
		}
		pair<int, int> a = djistra(1);
		printf("%d\n", djistra(a.first).second);
	}//while
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值