SPFA最短路Java模板
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
}
static int MAXN = 10000 + 10;
static int[] head = new int[MAXN];
static int[] nxt = new int[MAXN << 1];
static Node[] edge = new Node[MAXN << 1];
static boolean[] vis = new boolean[MAXN];
static int[] dis = new int[MAXN];
static int INF = 0x3f3f3f3f;
static int n, tot = 1;
static void add(int x, int y, int cost) {
edge[tot] = new Node(x, y, cost);
nxt[tot] = head[x];
head[x] = tot ++;
}
static void spfa(int x) {
for(int i = 1; i <= n; i ++) {
dis[i] = INF;
vis[i] = false;
}
Queue<Integer> q = new LinkedList<Integer>();
dis[x] = 0;
vis[x] = true;
q.offer(x);
while(!q.isEmpty()) {
int u = q.poll();
vis[u] = false;
for(int i = head[u]; i > 0; i = nxt[i]) {
int v = edge[i].y;
if(dis[v] > dis[u] + edge[i].cost) {
dis[v] = dis[u] + edge[i].cost;
if(!vis[v]) {
vis[v] = true;
q.offer(v);
}
}
}
}
}
static class Node {
int x, y, cost;
public Node(int x, int y, int cost) {
this.x = x;
this.y = y;
this.cost = cost;
}
}
}