출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]

상세 컨텐츠

본문 제목

백준 1613 역사(floyd-warshall)

알고리즘

by 장동균 2020. 8. 4. 23:54

본문

https://www.acmicpc.net/problem/1613

 

1613번: 역사

첫째 줄에 첫 줄에 사건의 개수 n(400 이하의 자연수)과 알고 있는 사건의 전후 관계의 개수 k(50,000 이하의 자연수)가 주어진다. 다음 k줄에는 전후 관계를 알고 있는 두 사건의 번호가 주어진다. ��

www.acmicpc.net

#include <iostream>

using namespace std;
const int MAX = 400 + 1;
int n, k;
int graph[MAX][MAX];

void floyd()
{
    for (int via = 1; via <= n; via++)
    {
        for (int from = 1; from <= n; from++)
        {
            if (graph[from][via] == 0)
                continue;
            for (int to = 1; to <= n; to++)
            {
                if (from == to || graph[via][to] == 0)
                    continue;
                if (graph[from][to] == 0)
                {
                    if (graph[from][via] == -1 && graph[via][to] == -1)
                        graph[from][to] = -1;
                    else if (graph[from][via] == 1 && graph[via][to] == 1)
                        graph[from][to] = 1;
                }
            }
        }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cin >> n >> k;
    for (int i = 0; i < k; i++)
    {
        int node1, node2;
        cin >> node1 >> node2;
        graph[node1][node2] = -1;
        graph[node2][node1] = 1;
    }
    floyd();

    int num;
    cin >> num;
    for (int i = 0; i < num; i++)
    {
        int num1, num2;
        cin >> num1 >> num2;
        cout << graph[num1][num2] << "\n";
    }
    // for(int i=1;i<=n;i++){
    //     for(int j=1;j<=n;j++){
    //         cout<<graph[i][j]<<" ";
    //     }
    //     cout<<"\n";
    // }
}

dfs 분류의 문제들을 꾸준히 풀고 있었는데 이 문제는 누가봐도 플로이드 와샬 문제였고 문제 분류에도 플로이드 와샬이 같이 있길래 플로이드 와샬로 풀었다. 연결할 때 값을 다르게 넣는다는 것 말고는 다를 것이 없다. 골드 3치고 쉬운 문제인 것 같다...

관련글 더보기

댓글 영역