PAT1003 带权图的最短路径

1003 Emergency (25分)

As an emergency rescue team leader of a city, you are given a special map of your country. The map shows several scattered cities connected by some roads. Amount of rescue teams in each city and the length of each road between any pair of cities are marked on the map. When there is an emergency call to you from some other city, your job is to lead your men to the place as quickly as possible, and at the mean time, call up as many hands on the way as possible.

Input Specification:

Each input file contains one test case. For each test case, the first line contains 4 positive integers: N (≤500) - the number of cities (and the cities are numbered from 0 to N−1), M - the number of roads, C1 and C2 - the cities that you are currently in and that you must save, respectively. The next line contains N integers, where the i-th integer is the number of rescue teams in the i-th city. Then M lines follow, each describes a road with three integers c1, c2 and L, which are the pair of cities connected by a road and the length of that road, respectively. It is guaranteed that there exists at least one path from C1 to C2.

Output Specification:

For each test case, print in one line two numbers: the number of different shortest paths between C1 and C2, and the maximum amount of rescue teams you can possibly gather. All the numbers in a line must be separated by exactly one space, and there is no extra space allowed at the end of a line.

Sample Input:

5 6 0 2  // 分别是 城市数量5   路的数量 6  你所在的城市0  需要救急的城市 2
1 2 1 5 3  // 每个城市拥有的人手
0 1 1    // 城市编号  城市标号 路的长度
0 2 2
0 3 1
1 2 1
2 4 1
3 4 1   

Sample Output:

2 4   

题目大意:

有N个城市,每个城市都有一定数量的工作人员。 N个城市之间有M条路,并给出每条路的长度。现在问我们,从一城市到另一个城市的最短路径有多少条。 并且输出最短路径上 可以召集的最多的人手。

这又是一个典型的图的最短路径问题,并且这幅图带有 顶点权(每个城市的人手)和边权(城市之间的路径长度)。我在第一版代码中思想比较简单 : 在遍历中找出所有的可达路径,保存这些路径,然后把这些路径按照总距离进行排序 ,通过条件输出最后的答案。 可想而知,这样做事费时费空间的(一个测试超时)。 其实这样回答问题属于回答多了。 什么叫回答多了呢? 人家只是问题有多少条最短路,并没有问最短路是谁。 举个例子,同学问你吃饭了没有,你只需要回答:吃了或者没吃,不用回答吃了什么东西。

思路分析:

有兴趣的同学直接阅读我的第二版代码即可。精简了很多。依然是通过DFS深度优先遍历进行从起点城市遍历到终点城市,在遍历过程中记住 路径的总长度 length 和路径上的总人数totalPeople

当我们遍历到终点城市时,把 lengthtotalPeople 拿出来和之前存储的 最短路径长度进行比较,首先比较的就是 length 路径的总长度,如果这个长度比之前的最短长度还要长的话,说明这是不符合要求的(我们要找最短的)此时什么都不做,递归可以返回了。

如果当前的length 和之前保存的最短路径长度一样长。 说明我们 又 找到了一条最短路。 最短路的条数 ++ 。 然后在比较一下当前这条路径上的总人数 是不是比之前存储的最短路径上的最大人数要大。 如果更大,我们就更新这个最大人数。然后就可以返回了。

如果当前的length 比之前保存的最短路径长度还要 短。 说明这是目前为止最短的。之前的都不算数。此时最短路径的条数应该更新为1 ,同时最短路径上的最大可以召集的人数应该为当前这条路径上的人数。 做完这个函数也就可以返回了。

上面三种情况都是递归终止是需要做的。如果当前的城市不是终点城市,那么我们就再向下递归一层。 不要忘记在递归中更新路径长度,路径上的人数。

完整代码:

// 第一版 回答问题多了 没有问具体路径  如果没有兴趣 可以不看。这里求出了所有的路径 并且保存了下来
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Main {
	static class Pair implements Comparable<Pair> {
		List<Integer> path;
		int length;

		public Pair(List<Integer> path, int length) {
			this.path = path;
			this.length = length;
		}

		@Override
		public int compareTo(Pair o) {
			if (this.length < o.length)
				return -1;
			else if (this.length == o.length)
				return 0;
			else
				return 1;
		}
	}

	private static int[][] roads;
	private static boolean[] used;
	private static List<Pair> paths;
	private static int[] people;

	public static void main(String[] args) {

		Scanner input = new Scanner(System.in);
		int cityNum = input.nextInt();
		int roadNum = input.nextInt();
		int myCity = input.nextInt();
		int saveCity = input.nextInt();
		people = new int[cityNum];
		for (int i = 0; i < cityNum; i++) {
			int peoples = input.nextInt();
			people[i] = peoples;
		}

		roads = new int[cityNum][cityNum];

		for (int i = 0; i < roadNum; i++) {

			int city1 = input.nextInt();
			int city2 = input.nextInt();
			int length = input.nextInt();
			roads[city1][city2] = length;
			roads[city2][city1] = length;
		}


		used = new boolean[cityNum];
		paths = new ArrayList<Pair>();
		List<Integer> path = new ArrayList<>();

		DFS(roads, myCity, saveCity, path, 0);

		// 找出最短路径 条数 和可以召集的最多人数

		Collections.sort(paths);

		int minLen = paths.get(0).length;
		int maxNUM = 0;
		for (int i = 0; i < paths.get(0).path.size(); i++) {
			maxNUM += people[paths.get(0).path.get(i)];

		}

		int distnum = 1;

		for (int i = 1; i < paths.size() && paths.get(i).length == minLen; i++) {
			distnum++;
			int num = getpeopleNUM(paths.get(i).path);
			if (num > maxNUM)
				maxNUM = num;
		}

		System.out.printf("%d %d", distnum, maxNUM);

	}

	// DFS进行寻路
	private static void DFS(int[][] roads, int currentCity, int saveCity, List<Integer> path, int length) {
		if (currentCity == saveCity) {
			used[currentCity] = true;
			path.add(saveCity);
			paths.add(new Pair(new ArrayList<>(path), length));
			return;
		}
		path.add(currentCity);
		used[currentCity] = true;
		for (int i = 0; i < roads.length; i++) {
			if (roads[currentCity][i] != 0 && !used[i]) {

				DFS(roads, i, saveCity, path, length + roads[currentCity][i]);
				used[i] = false;
				path.remove(path.size() - 1);
			}
		}
		return;
	}

	public static int getpeopleNUM(List<Integer> path) {
		int res = 0;
		for (int i = 0; i < path.size(); i++)
			res += people[path.get(i)];
		return res;
	}

}

// 第二版代码,精简了许多 只回答需要回答的问题
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main  {

	private static int[][] roads;  // 图的邻接矩阵存储
    private static boolean[] used; // 访问标记数组
    private static int[] people;  // 每个城市拥有的人手
    private static int minLengh = Integer.MAX_VALUE; // 当前找到的最短的路径
    private static int maxCount = Integer.MIN_VALUE; // 当前最短路径中获得的最多的人数
    private static int minRoadCount = 0; // 最短路径的条数


    public static void main(String[] args) throws IOException {

        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        String[] info = input.readLine().split(" "); 
        int cityNum = Integer.parseInt(info[0]); // 城市的数量
        int roadNum = Integer.parseInt(info[1]); // 路的数量
        int myCity = Integer.parseInt(info[2]); // 起点城市
        int saveCity = Integer.parseInt(info[3]); // 终点城市
        String[] peopleNum = input.readLine().split(" "); 
        people = new int[cityNum];
        for (int i = 0; i < cityNum; i++) { //每个城市有多少人
         	people[i] = Integer.parseInt(peopleNum[i]);
        }
        roads = new int[cityNum][cityNum];

        for (int i = 0; i < roadNum; i++) {
            String[] roadInfo = input.readLine().split(" ");
            int city1 = Integer.parseInt(roadInfo[0]); // 城市编号1
            int city2 = Integer.parseInt(roadInfo[1]); // 城市编号2
            int length = Integer.parseInt(roadInfo[2]); // 城市1和城市2之间的路的长度
            roads[city1][city2] = length;  // 我们这里存储的是无向图
            roads[city2][city1] = length;
        }
        used = new boolean[cityNum];
        DFS(roads, myCity, saveCity, people[myCity], 0);
        System.out.printf("%d %d",minRoadCount ,maxCount);

    }

    // DFS进行寻路  totalPeople 路径上的总人数  length 路径的长度
    private static void DFS(int[][] roads, int currentCity, int saveCity, int totalPeople, int length) {
        if (currentCity == saveCity) {
            used[currentCity] = true;
            if (length < minLengh) { // 新的最短路径出现了
				minLengh = length ;
				maxCount = totalPeople ;// 更新人数 之前的最大人数都不算,因为刚刚出现的路径比之前的都短
				minRoadCount = 1; // 更新最短路径的条数为1
            }else  if(length == minLengh){ // 如果这条路和之前最短的一样短
            	minRoadCount ++ ; //说明又出现了一条最短路 最短路径条数+1
            	if(totalPeople > maxCount) // 如果这条路上的人数比之前最短路上的人数多 
            		maxCount = totalPeople; //更新最大人数
			}
        return;
        }
        used[currentCity] = true;
        for (int i = 0; i < roads.length; i++) {
            if (roads[currentCity][i] != 0 && !used[i]) {
                DFS(roads, i, saveCity, totalPeople+people[i] , length + roads[currentCity][i]);
                used[i] = false;
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值