无环有向图最长路径

1、把dist 初始为负无穷

2、松弛判断条件改为 dist[v] < dist[u] + w;

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;

import Graph.HasCycle;
import javafx.scene.effect.Light.Distant;

public class TopDij {
	static boolean[]visit;
	static boolean[]onStack;
	static Stack<Integer> stack;
	static int n, m;
	static boolean hasCycle = false;
	static int[]dis;
	static int INF = 99999999;
	static ArrayList<EdgeS> []adj;
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		n = in.nextInt();
		m = in.nextInt();
		visit = new boolean[n+1];
		adj = new ArrayList[n+1];
		stack = new Stack<>();
		dis = new int[n+1];
		onStack = new boolean[n+1];
		for(int i = 1; i <= n; i++ ) {
			adj[i] = new ArrayList<>();
		}
		for(int i = 0; i < m; i++ ) {
			int from = in.nextInt();
			int to = in.nextInt();
			int w = in.nextInt();
			adj[from].add(new EdgeS(from, to, w));
		}
		bfs(1);
		if(!hasCycle) {
			shortPath(1);
			System.out.println(dis[3]);
		}
		else {
			System.out.println("hasCycle");
		}
	}
	public static void shortPath(int s) {
		for(int i = 1; i <= n; i++ ) {
			dis[i] = -INF;
		}
		dis[s] = 0;
		while(!stack.isEmpty()) {
			int cur = stack.pop();
			for(EdgeS e: adj[cur]) {
				if(dis[e.to] < dis[cur] + e.w) {
					dis[e.to] = dis[cur] + e.w;
				}
			}
		}
		
	}
	public static void bfs(int cur) {
		visit[cur] = true;
		onStack[cur] = true;
		for(EdgeS e:adj[cur]) {
			if(!visit[e.to]) {
				bfs(e.to);
			}
			else if(onStack[e.to]){
				hasCycle = true;
				return;
			}
		}
		onStack[cur] = false;
		stack.push(cur);
	}
}
class EdgeS{
	int from, to, w;
	public EdgeS(int f, int t, int w) {
		from = f;
		to = t;
		this.w = w;
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值