已過測試用例的java代碼如下
利用了dfs的思想.對於每條路,深度優先搜索其通往的道路.visited在遍歷中設置爲true,在遍歷此節點過後設置爲false
public class PAT1003 {
private static int shortestPath = Integer.MAX_VALUE;
private static int shortCount = 0;
private static int maxAmount = 0;
private static int destPos;
private static int[] teamCountArray;
private static int[][] roadLenArray;
private static boolean[] visited;
private static int cityCount;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
cityCount = scanner.nextInt();
int roadCount = scanner.nextInt();
int currentPos = scanner.nextInt();
destPos = scanner.nextInt();
teamCountArray = new int[cityCount];
visited = new boolean[cityCount];
for (int i = 0; i < cityCount; i++) {
teamCountArray[i] = scanner.nextInt();
}
roadLenArray = new int[cityCount][cityCount];
for (int i = 0; i < cityCount; i++) {
for (int j = 0; j < cityCount; j++) {
roadLenArray[i][j] = -1;
}
}
for (int i = 0; i < roadCount; i++) {
int src = scanner.nextInt();
int desc = scanner.nextInt();
int len = scanner.nextInt();
roadLenArray[src][desc] = len;
roadLenArray[desc][src] = len;
}
for (int i = 0; i < cityCount; i++) {
visited[i] = false;
}
visited[currentPos] = true;
if(currentPos == destPos){
System.out.println("1" + " " + teamCountArray[currentPos]);
}else{
dfs(currentPos, 0, teamCountArray[currentPos]);
System.out.println(shortCount + " " + maxAmount);
}
}
static void dfs(int start, int pathLen, int teamCount) {
for (int i = 0; i < cityCount; i++) {
if (roadLenArray[start][i] != -1) {
if (i == destPos) {
int newPathLen = pathLen + roadLenArray[start][i];
int newTeamCount = teamCount + teamCountArray[i];
if (newPathLen < shortestPath) {
maxAmount = newTeamCount;
shortCount = 1;
shortestPath = newPathLen;
} else if (newPathLen == shortestPath) {
maxAmount = maxAmount > newTeamCount ? maxAmount : newTeamCount;
shortCount++;
}
visited[i] = false;
continue;
}
if (!visited[i]) {
//未遍歷過
if (pathLen + roadLenArray[start][i] <= shortestPath) {
visited[i] = true;
dfs(i, pathLen + roadLenArray[start][i], teamCount + teamCountArray[i]);
visited[i] = false;
}
}
}
}
}
}