본문 바로가기

라이브러리/JAVA

벨만 포드

전처리

static class Wrapper
{
    int[] dist;
    boolean is_cycle;
    Wrapper (int[] dist, boolean is_cycle) { this.dist = dist; this.is_cycle = is_cycle; }
}

static class Edge
{
    int u, v, w;
    Edge (int u, int v, int w) { this.u = u; this.v = v; this.w = w; }
}

for (int i=0; i<M; i++)
{
    st = new StringTokenizer(input.readLine());

    int u = Integer.parseInt(st.nextToken());
    int v = Integer.parseInt(st.nextToken());
    int w = Integer.parseInt(st.nextToken());

    G.add( new Edge(u, v, w) );
}

 

 

 

 

벨만 포드

static Wrapper Bellman_Ford (ArrayList<Edge> G, int N, int INF)
{
    boolean is_cycle = false;
    int[] dist = new int[N+1];

    for (int i=1; i<=N; i++)
        dist[i] = INF;

    for (int i=0; i<N; i++)
    {
        for (int j=0; j<G.size(); j++)
        {
            int u = G.get(j).u;
            int v = G.get(j).v;
            int w = G.get(j).w;

            if ( dist[u] + w < dist[v] )
            {
                dist[v] = dist[u] + w;

                if ( i == N-1 )
                {
                    is_cycle = true;
                    break;
                }
            }
        }
    }
    return new Wrapper(dist, is_cycle);
}

'라이브러리 > JAVA' 카테고리의 다른 글

사이클 최소합  (1) 2024.08.10
변형 인접리스트  (0) 2024.08.08
히스토그램 최대 넓이  (0) 2024.07.15
에라체  (0) 2024.07.08
분할정복 거듭제곱  (1) 2024.07.08