1003. Emergency (25)
生词以及在文中的意思:
scattered 分散的
/*
* 定义dist为当前路径长度,WeiSum定义min为最后结果中路径最小值。定义cnt为最短路径条数,初始为0,
* 之后在dfs过程一旦找到路径长度和小于min的情况,则
* cnt变为1,如果找到不同的路径长度和等于min的情况,则cnt++,这里还要再比较。在dfs前先将每两个定点间
* 的路长初始化为int型最大值,表示两点间不存在路径。并初始化visited数组 为0
* ,表示没有顶点被访问过。随后输入路径信息。递归结束条件为dist>min
*/
import java.util.Scanner; public class Main { static int[] visited = new int[600]; static int[][] road = new int[600][600]; static int[] wei = new int[600]; static int min = Integer.MAX_VALUE; static int cnt = 0; static int max = 0; static int n, m; public static void main(String[] args) { // TODO Auto-generated method stub int st, end; Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); st = sc.nextInt(); end = sc.nextInt(); init(n); for (int i = 0; i < n; i++) { wei[i] = sc.nextInt(); } for (int i = 0; i < m; i++) { int x = sc.nextInt(); int y = sc.nextInt(); int dis = sc.nextInt(); road[x][y] = dis; road[y][x] = dis; } dfs(st, end, 0, wei[st]); System.out.print(cnt + " " + max); } static void init(int n) { for (int i = 0; i < n; i++) { visited[i] = 0; for (int j = 0; j < n; ++j) { road[i][j] = Integer.MAX_VALUE; } } } static void dfs(int st, int end, int dist, int WeiSum) { if (st == end) { if (dist < min) { min = dist; cnt = 1; max = WeiSum; } else if (dist == min) { cnt++; if (WeiSum > max) { max = WeiSum; } } return; } if (dist > min) { return; } for (int i = 0; i < n; i++) { if (visited[i] == 0 && road[st][i] != Integer.MAX_VALUE) { visited[i] = 1; dfs(i, end, dist + road[st][i], WeiSum + wei[i]); visited[i] = 0; } } } }
如有改进建议,请提出,不胜感激!