/*UVa 558 - Wormholes
* 使用邻接表存储图
* */
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
static final int MAX = 1 << 20;
static final int N = 1005;
static final int M = 2005;
int[] u = new int[M];// 边的起点
int[] v = new int[M];// 边的终点
int[] w = new int[M];// 边权
int[] first = new int[M];// frist[u]以u为起点的第一条边
int[] next = new int[M];// next[i]编号为i的边的下一条边
int[] d = new int[N];
int[] count = new int[N];// 节点进队列的次数
int[] inq = new int[N];// 节点是否在队列中
LinkedList<Integer> queue = new LinkedList<Integer>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int c = scanner.nextInt();
Main main = new Main();
while (c > 0) {
c--;
int n = scanner.nextInt();
int m = scanner.nextInt();
Arrays.fill(main.first, -1);// 初始化表头
for (int e = 0; e < m; e++) {
main.u[e] = scanner.nextInt();
main.v[e] = scanner.nextInt();
main.w[e] = scanner.nextInt();
main.next[e] = main.first[main.u[e]];
main.first[main.u[e]] = e;
}
if (main.SPFA(n))
System.out.println("possible");
else
System.out.println("not possible");
}
}
private boolean SPFA(int n) {
Arrays.fill(d, MAX);
Arrays.fill(count, 0);
Arrays.fill(inq, 0);
d[0] = 0;
queue.clear();
queue.offer(0);
count[0]++;
while (queue.size() > 0) {
int x = queue.poll();
inq[x] = 0;// 清除在队列中标识
for (int e = first[x]; e != -1; e = next[e]) {
if (d[v[e]] > d[x] + w[e]) {
d[v[e]] = d[x] + w[e];
if (inq[v[e]] == 0) {// 不在队列中才添加
inq[v[e]] = 1;
count[v[e]]++;
queue.offer(v[e]);
if (count[v[e]] >= n) {// 存在负环
return true;
}
}
}
}
}
return false;
}
}
UVa 558 - Wormholes
最新推荐文章于 2020-02-21 17:32:34 发布