본문 바로가기

운동하는 개발자/알고리즘, 코딩테스트

Beakjoon] 줄 세우기(백준 11657 코테) - 그래프 (C++) (벨만-포드)

728x90


🅰️문제주소 : https://www.acmicpc.net/problem/11657

 


🚩문제 

 

 

🪡풀이 

 - 최단거리를 구하는데 음수가 가능한 경우는 벨만-포드 알고리즘을 사용
에지정보를 tuple로 저장해둔다.
그리고 노드의 개수 -1만큼 반복 뒤 마지막 한번 더 진행시 업데이트 되는 값이 있는 경우 
음수 사이클이 존재하므로 -1을 출력시킨다 (음수 사이클이 존재하면 무한대로 돌면 무한대로 최단거리가 짧아지므로..)

 

☕코드는 아래 숨김

더보기

#include <iostream>
#include <tuple>
#include <vector>
#include <limits.h>

using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    typedef tuple<int, int, int> edge;
    int N, M;
    vector<long> mdistance;
    vector<edge> edges;

    cin >> N >> M;

    mdistance.resize(N + 1);
    fill(mdistance.begin(), mdistance.end(), LONG_MAX);

    for (int i = 0; i < M; ++i)
    {
        int start, end, time;
        cin >> start >> end >> time;
        edges.push_back(make_tuple(start, end, time));
    }

    mdistance[1] = 0;

    for (int i = 1; i < N; ++i)
    {
        for (int j = 0; j < M; ++j)
        {
            edge medge = edges[j];
            int start = get<0>(medge);
            int end = get<1>(medge);
            int time = get<2>(medge);
            if (mdistance[start] != LONG_MAX && mdistance[end] > mdistance[start] + time)
                mdistance[end] = mdistance[start] + time;
        }
    }

    bool mCycle = false;
    for (int j = 0; j < M; ++j)
    {
        edge medge = edges[j];
        int start = get<0>(medge);
        int end = get<1>(medge);
        int time = get<2>(medge);
        if (mdistance[start] != LONG_MAX && mdistance[end] > mdistance[start] + time)
            mCycle = true;
    }

    if (mCycle == false)
    {
        for (int i = 2; i <= N; ++i)
        {
            if (mdistance[i] == LONG_MAX)
                cout << -1 << "\n";
            else
                cout << mdistance[i] << "\n";
        }
    }
    else
        cout << -1 << "\n";

    

    return 0;
}

 

💡알게 된 것 

 - 벨만-포드 알고리즘
 - tuple사용법 remind


 

728x90