这道题我的第一思路是Floyd,时间复杂度是1000*1000*1000,肯定超时
所以用Dijkstra,用两次就行了,去一次,回来一次,由于图是单向的,所以我建立的两张图(一张是起点与终点反过来的),都是以聚会地点为起点,到各个点的距离
package _03___图论;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Scanner;
public class _03_POJ_3268 {
//1.定义图
//list数组,图的邻接表
public static List<Node>[] G;
//2.定义d数组,表示距离
public static int d[];
//3.定义p数组,表示上一个的路径
public static int p[];
//5.定义inq数组,用于记录某点是否加入队列
public static boolean inq[];
//6.优先级队列。
public static PriorityQueue <int[]> queue;
//7.图的点数
public static int N;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//给N赋值
N = sc.nextInt();
//初始化图的数组
G = new List[N+1];
List<Node>[] G2 = new List[N+1];
for (int j = 0; j < N+1; j++)G[j] = new ArrayList<Node>();
for (int j = 0; j < N+1; j++)G2[j] = new ArrayList<Node>();
int M = sc.nextInt();
int X = sc.nextInt();
for (int i = 0; i < M; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
G[a].add(new Node(a, b, c));
G2[b].add(new Node(b, a, c));
}
dijkstra(X);
int[] d1 = d;
G=G2;
dijkstra(X);
int[] d2 = d;
int max = Integer.MIN_VALUE;
for (int i = 0; i < d1.length; i++) {
max = Math.max(max, d1[i]+d2[i]);
}
System.out.println(max);
}
private static void dijkstra(int s) {
//初始化数组
d = new int[N+1];
Arrays.fill(d, Integer.MAX_VALUE);
d[s] = 0;
p = new int[N+1];
inq = new boolean[N+1];
queue =new PriorityQueue<int[]>(new Mysort());
queue.offer(new int[]{s,0});
while(!queue.isEmpty()) {
int[] us = queue.poll(); //弹出值最小的点 (点,距离)
int u = us[0];
if(inq[u])continue;//如果这个点被使用过,bfs思想
inq[u] = true; //开始使用
for (int i = 0; i < G[u].size(); i++) {
Node node = G[u].get(i);
if(d[node.to]>d[node.from]+node.dist) {
d[node.to]=d[node.from]+node.dist;
p[node.to]=node.from;
//需要把到达的这个点加入队列
queue.add(new int[]{node.to,us[1]+node.dist});
}
}
}
}
}
class Node{
int from;
int to;
int dist;
public Node(int from,int to,int dist) {
this.from = from;
this.to = to;
this.dist = dist;
}
}
class Mysort implements Comparator<int[]>{
@Override
public int compare(int[] arg0, int[] arg1) {
return arg0[1]-arg1[1];
}
}