2009合肥网赛H题解题报告

本文介绍了一种利用Dijkstra算法解决最短路径问题的方法,并通过一个具体的编程实例展示了如何求解两点间经过所有其他点的最短路径总和。文章首先使用Dijkstra算法计算每个点到其它所有点的最短距离,然后通过枚举所有点对来找出最优解。

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

这道题先直接求出每个点到其他点的最短距离,然后再枚举每一种组合。可以用dijkstra或者floyed都行!

http://acm.ustc.edu.cn/ustcoj/problem.php?id=1123

team579AcceptedJava1600ms27672kb2307

import java.util.Arrays; import java.util.Scanner; public class Main { private static int n; private static int[][] dist = new int[501][501]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int testNum = sc.nextInt(); for (int i = 0; i < testNum; i++) { n = sc.nextInt(); int e = sc.nextInt(); int[][] map = new int[e + 1][e + 1]; boolean[] visted = new boolean[n + 1]; for (int j = 1; j <= e; j++) { int a = sc.nextInt(); int b = sc.nextInt(); int t = sc.nextInt(); if (a == b) continue; else if (map[a][b] == 0) { map[a][b] = t; map[b][a] = t; } else if (map[a][b] != 0 && map[a][b] > t) { map[a][b] = t; map[b][a] = t; } } solve(map, visted); } } public static void solve(int[][] map, boolean[] visted) { int sum = Integer.MAX_VALUE; int ans1 = -1; int ans2 = -1; for (int i = 1; i <= n; i++) { dijkstra(map, visted, dist[i], i); } for (int i = 1; i < n; i++) { for (int j = i + 1; j <= n; j++) { int tempSum = 0; for (int k = 1; k <= n; k++) { if (dist[i][k] != Integer.MAX_VALUE && dist[j][k] != Integer.MAX_VALUE && k != i && k != j) { if (dist[i][k] > dist[j][k]) { tempSum += dist[j][k]; } else { tempSum += dist[i][k]; } } } if (sum > tempSum) { sum = tempSum; ans1 = i; ans2 = j; } } } System.out.println(ans1 + " " + ans2); } public static void dijkstra(int[][] map, boolean[] visted, int[] dist, int s) { Arrays.fill(visted, false); Arrays.fill(dist, Integer.MAX_VALUE); for (int i = 1; i <= n; i++) { if (map[s][i] != 0 && !visted[i]) dist[i] = map[s][i]; } visted[s] = true; int temp = 0; while (true) { int min = Integer.MAX_VALUE; temp = 0; for (int i = 1; i <= n; i++) { if (!visted[i] && min > dist[i]) { min = dist[i]; temp = i; } } if (temp == 0) break; visted[temp] = true; for (int i = 1; i <= n; i++) { if (!visted[i] && map[temp][i] != 0 && dist[i] > dist[temp] + map[temp][i]) { dist[i] = dist[temp] + map[temp][i]; } } } } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值