Farthest Nodes in a Tree

本文介绍了一道算法题目:在一个带权无向树中找到距离最远的两个节点,并给出了详细的输入输出样例及C++实现代码。
Farthest Nodes in a Tree
Time Limit:2000MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu

Description

Given a tree (a connected graph with no cycles), you have to find the farthest nodes in the tree. The edges of the tree are weighted and undirected. That means you have to find two nodes in the tree whose distance is maximum amongst all nodes.

Input

Input starts with an integer T (≤ 10), denoting the number of test cases.

Each case starts with an integer n (2 ≤ n ≤ 30000) denoting the total number of nodes in the tree. The nodes are numbered from 0 to n-1. Each of the next n-1 lines will contain three integers u v w (0 ≤ u, v < n, u ≠ v, 1 ≤ w ≤ 10000) denoting that node u and v are connected by an edge whose weight is w. You can assume that the input will form a valid tree.

Output

For each case, print the case number and the maximum distance.

Sample Input

2

4

0 1 20

1 2 30

2 3 50

5

0 2 20

2 1 10

0 3 29

0 4 50

Sample Output

Case 1: 100

Case 2: 80

怎么说呢,注意数组,别再开小了。。不然又是Runtime Error!!大致上跟Cow Marathon题一样。

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#define MAXN 60000+10
using namespace std;
struct Edge {
    int from, to, val, next;
}edge[MAXN * 2];
int head[MAXN];
int edgenum;
void init(){
	memset(head, -1, sizeof(head)); 
	edgenum = 0; 
}
void addEdge(int u, int v, int w) {
    Edge E = {u,v,w,head[u]};
    edge[edgenum]=E;
    head[u] = edgenum++;
}
int ans;
int Tnode;
int dist[MAXN];
bool vis[MAXN];
int n;
void BFS(int s) {
    memset(dist, 0, sizeof(dist)); 
	memset(vis, false, sizeof(vis));
    queue<int> Q; 
	Q.push(s); 
	vis[s] = true; 
	dist[s] = 0; ans = 0;
    while(!Q.empty()) {
        int u = Q.front(); 
		Q.pop();
        for(int i = head[u]; i != -1; i = edge[i].next) {
            int v = edge[i].to;
            if(!vis[v]&&dist[v] < dist[u] + edge[i].val) {
                vis[v] = true;
                dist[v] = dist[u] + edge[i].val;
                if(dist[v] > ans) {
            		ans = dist[v];
            		Tnode = v;
        		}
                Q.push(v);
            }
        }
    }
}
int main(){
	int t,a,b,c,count=1;
	scanf("%d",&t);
	while(t--){
		scanf("%d",&n);
		init();
		for(int i=1;i<n;i++){
			scanf("%d%d%d",&a,&b,&c);
			a++;b++;
			addEdge(a,b,c);
			addEdge(b,a,c);
		}
		BFS(1);
		BFS(Tnode);
		printf("Case %d: %d\n",count++,ans);
	}
}

from collections import defaultdict, deque import sys def build_graph(file_path): """从文件构建无向图""" graph = defaultdict(list) nodes = set() with open(file_path, 'r') as f: for line in f: line = line.strip() if not line or '-' not in line: continue a, b = line.split('-', 1) # 只分割第一个'-' a, b = a.strip(), b.strip() if a and b: graph[a].append(b) graph[b].append(a) nodes.add(a) nodes.add(b) return graph, nodes def break_cycles(graph, nodes): """断开图中所有环,返回生成森林""" visited = set() parent = {} forest = defaultdict(list) # 存储生成森林 for node in nodes: if node not in visited: stack = [node] visited.add(node) parent[node] = None while stack: cur = stack.pop() for neighbor in graph[cur]: # 忽略父节点 if neighbor == parent[cur]: continue # 遇到已访问节点(回边),跳过添加 if neighbor in visited: continue # 添加树边到森林 visited.add(neighbor) parent[neighbor] = cur forest[cur].append(neighbor) forest[neighbor].append(cur) stack.append(neighbor) return forest def find_tree_diameter(component, forest): """计算树的直径和路径""" def bfs(start): dist = {} pred = {} q = deque([start]) dist[start] = 0 pred[start] = None farthest_node = start while q: cur = q.popleft() for neighbor in forest[cur]: if neighbor not in dist: dist[neighbor] = dist[cur] + 1 pred[neighbor] = cur q.append(neighbor) if dist[neighbor] > dist[farthest_node]: farthest_node = neighbor return farthest_node, dist, pred # 第一次BFS找最远端点 start = next(iter(component)) u, dist_u, _ = bfs(start) # 第二次BFS找直径 v, dist_v, pred = bfs(u) # 重建路径 path = [] cur = v while cur is not None: path.append(cur) cur = pred.get(cur, None) return len(path), path # 返回节点数和路径 def find_connected_components(forest, nodes): """在生成森林中找连通分量""" visited = set() components = [] for node in nodes: if node not in visited: comp = set() stack = [node] visited.add(node) while stack: cur = stack.pop() comp.add(cur) for neighbor in forest[cur]: if neighbor not in visited: visited.add(neighbor) stack.append(neighbor) components.append(comp) return components def main(file_path): # 1. 构建原始图 graph, all_nodes = build_graph(file_path) # 2. 断开所有环得到生成森林 forest = break_cycles(graph, all_nodes) # 3. 获取连通分量(树) components = find_connected_components(forest, all_nodes) # 4. 计算每棵树的直径 max_chain_length = 0 max_chain_path = [] for comp in components: if not comp: continue length, path = find_tree_diameter(comp, forest) if length > max_chain_length: max_chain_length = length max_chain_path = path # 5. 输出结果 print(f"最长链长度(节点数): {max_chain_length}") print(f"最长链路径: {' -> '.join(max_chain_path)}") if __name__ == "__main__": if len(sys.argv) != 2: print("G:\研究生\分子对应\99999.txt") sys.exit(1) main(sys.argv[1]) 咋输入这个文件地址啊
12-12
(SCI三维路径规划对比)25年最新五种智能算法优化解决无人机路径巡检三维路径规划对比(灰雁算法真菌算法吕佩尔狐阳光生长研究(Matlab代码实现)内容概要:本文档主要介绍了一项关于无人机三维路径巡检规划的研究,通过对比2025年最新的五种智能优化算法(包括灰雁算法、真菌算法、吕佩尔狐算法、阳光生长算法等),在复杂三维环境中优化无人机巡检路径的技术方案。所有算法均通过Matlab代码实现,并重点围绕路径安全性、效率、能耗和避障能力进行性能对比分析,旨在为无人机在实际巡检任务中的路径规划提供科学依据和技术支持。文档还展示了多个相关科研方向的案例与代码资源,涵盖路径规划、智能优化、无人机控制等多个领域。; 适合人群:具备一定Matlab编程基础,从事无人机路径规划、智能优化算法研究或自动化、控制工程方向的研究生、科研人员及工程技术人员。; 使用场景及目标:① 对比分析新型智能算法在三维复杂环境下无人机路径规划的表现差异;② 为科研项目提供可复现的算法代码与实验基准;③ 支持无人机巡检、灾害监测、电力线路巡查等实际应用场景的路径优化需求; 阅读建议:建议结合文档提供的Matlab代码进行仿真实验,重点关注不同算法在收敛速度、路径长度和避障性能方面的表现差异,同时参考文中列举的其他研究案例拓展思路,提升科研创新能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值