题目连接:最长路 - 洛谷
题目大意:给定n个点,m条边,求1到n的最长路(n <= 1500; m <= 50000)
输入格式:
输入的第一行有两个整数,分别代表图的点数 n 和边数 m。
第 2 到第 (m+1) 行,每行 3 个整数 u,v,w(u<v),代表存在一条从 u 到 v 边权为 w 的边
输出格式:
输出一行代表答案,若无法到达输出-1
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;
public class 最长路 {
static int n, m;
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static class Edge{
int to, weight;
public Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
static ArrayList<Edge>[] adjList = new ArrayList[2000];
public static void main(String[] args) throws IOException {
in.nextToken();
n = (int) in.nval;
in.nextToken();
m = (int) in.nval;
for (int i = 1; i <= n; i++) {
adjList[i] = new ArrayList<>();
}
int x,y,z;
for (int i = 0; i < m; i++) {
in.nextToken();
x = (int) in.nval;
in.nextToken();
y = (int) in.nval;
in.nextToken();
z = (int) in.nval;
adjList[x].add(new Edge(y, z));
}
// 优先队列按到源点的距离从大到小排序
Queue<int[]> queue = new PriorityQueue<>((a, b) -> b[1] - a[1]);
queue.add(new int[]{1, 0});
int[] dis = new int[n + 1];
// 权值可能为负数,不能设置为0
Arrays.fill(dis, Integer.MIN_VALUE);
dis[1] = 0;
while (!queue.isEmpty()){
int[] cur = queue.poll();
for (int i = 0; i < adjList[cur[0]].size(); i++) {
int t = adjList[cur[0]].get(i).to;
int w = adjList[cur[0]].get(i).weight;
if (dis[t] < w + dis[cur[0]]){
dis[t] = w + dis[cur[0]];
queue.add(new int[]{t, dis[t]});
}
}
}
System.out.println(dis[n] == Integer.MIN_VALUE ? -1 : dis[n]);
}
}