原题连接:
1003. Emergency
我的思路:
利用 DFS(深度优先搜索)从起点开始找路(同时记录路径长度和经过的各个节点)每找到一条可达路径,先判定这条路径的长度如果大于当前最短路则直接跳过如果等于当前最短路,则查看该路上可以集结几只队伍,如果队伍数大于当前最多队伍数,则更新,否则跳过如果小于当前最短路,则更新当前最短路,并更新当前最多队伍
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
private static List<Integer> path =
new ArrayList<>();
private static int minLength =
0, maxTeams =
0, thisLength =
0, viablePath =
0;
private static int[] teams;
private static boolean[] marked;
public static void main(String[] args) {
Scanner in =
new Scanner(System.in);
int[][] cityMap;
int n = in.nextInt();
int m = in.nextInt();
int from = in.nextInt();
int to = in.nextInt();
teams =
new int[n];
marked =
new boolean[n];
cityMap =
new int[n][n];
for (
int i =
0; i < n; i++){
teams[i] = in.nextInt();
}
for (
int i =
0; i < m; i++){
int start, end, len;
start = in.nextInt();
end = in.nextInt();
len = in.nextInt();
cityMap[start][end] = len;
cityMap[end][start] = len;
}
dfs(cityMap, from, to);
System.out.println(viablePath +
" " + (maxTeams + teams[from]));
}
private static void dfs(
int[][] map,
int from,
int to){
if (from == to) {
if (minLength <=
0 || thisLength <= minLength){
if (thisLength == minLength){
viablePath++;
}
else {
minLength = thisLength;
viablePath =
1;
maxTeams =
0;
}
int thisTeams =
0;
for (
int i =
0; i < path.size(); i++){
thisTeams += teams[path.get(i)];
}
if (thisTeams > maxTeams){
maxTeams = thisTeams;
}
}
return;
}
marked[from] =
true;
for (
int i =
0; i < map.length; i++){
if (map[from][i] >
0 && !marked[i]){
path.add(i);
thisLength += map[from][i];
dfs(map, i, to);
thisLength -= map[from][i];
path.remove(path.size() -
1);
}
}
marked[from] =
false;
}
}