UVa 558 - Wormholes

/*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;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值