08-图8 How Long Does It Take(25 分)(关键路径,java)

题目链接

08-图8 How Long Does It Take(25 分)

分析

其实就是求最长路,记忆化一下就好了

code

import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;


public class Main {
    public static Scanner in = new Scanner(new BufferedInputStream(System.in));
    public static final int INF32 = 0x3f3f3f3f;
    public static final int MAXN = 100+10;
    public static ArrayList<Edge>[] G = new ArrayList[MAXN];
    public static int n,m;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        n = in.nextInt();
        m = in.nextInt();
        for(int i=0 ; i<n ; ++i)G[i] = new ArrayList<>();
        for(int i=0 ; i<m ; ++i){
            int u = in.nextInt();
            int v = in.nextInt();
            int w = in.nextInt();
            G[u].add(new Edge(u, v, w));
        }
        solve();
    }
    public static int[] dp= new int[MAXN];
    public static boolean[] vis = new boolean[MAXN];
    public static boolean dfs(int v) {
        if(!vis[v]){
            vis[v] = true;
            if(dp[v] ==-1){
                if(G[v].size()==0)dp[v] =0;
                else for(Edge e: G[v]){
                    boolean ret = dfs(e.v);
                    if(!ret)return ret;
                    dp[v] = Math.max(dp[v], dp[e.v]+e.w);
                }
            }
        }
        else if(dp[v] ==-1)return false;// vis[v]=true;dp[v] = -1产生环 

        return true;
    }
    public static void solve() {
        Arrays.fill(vis, 0,n,false);
        Arrays.fill(dp,0,n, -1);
        for(int i=0 ; i<n ; ++i)
            if(!dfs(i)){
                System.out.println("Impossible");
                return;
            }
        int ans =0;
        for(int i=0 ; i<n ; ++i)ans = Math.max(ans, dp[i]);
        System.out.println(ans);
    }
}


class Edge implements Comparable<Edge>{
    int u,v,w;

    public Edge(int u, int v, int w) {
        super();
        this.u = u;
        this.v = v;
        this.w = w;
    }

    @Override
    public int compareTo(Edge o) {
        // TODO Auto-generated method stub
        return this.w - o.w;
    }

}

猜你喜欢

转载自blog.csdn.net/dylan_frank/article/details/80084322