DAMPER's 낙서장

1238 파티 본문

Problem Solving/BOJ 문제풀이

1238 파티

DAMPER 2021. 5. 5. 10:25
728x90

www.acmicpc.net/problem/1238

 

1238번: 파티

첫째 줄에 N(1 ≤ N ≤ 1,000), M(1 ≤ M ≤ 10,000), X가 공백으로 구분되어 입력된다. 두 번째 줄부터 M+1번째 줄까지 i번째 도로의 시작점, 끝점, 그리고 이 도로를 지나는데 필요한 소요시간 Ti가 들어

www.acmicpc.net

처음엔 플로이드 와샬 문제인 줄 알았지만 \( 1 \leq N \leq 1000 \) 이라 고민을 많이 했던 문제.

 

플로이드 와샬 문제라고 생각한 이유는 각각의 노드부터 x까지의 거리와 x부터 각각의 노드까지의 거리를 알아야 했기 때문이다.

 

단방향 그래프이기 때문에 각각의 노드부터 x까지의 거리x부터 각각의 노드까지의 거리가 같지않다.

 

그래서 '거의' 모든 경로를 알아야한다고 생각했지만

다익스트라 알고리즘을 N번하여 원하는 거리만 구할 수 있었다.

 

1.  x 부터 각각의 노드까지의 거리를 구한다.

2. 각각의 노드로부터 x까지의 거리를 구하고 x부터 각각의 노드까지의 거리를 더한다.

3. 최대값을 출력한다.

 

다익스트라 알고리즘을 N번 수행하기 때문에 시간복잡도는 \(  O(N(|E|+|V|log|V|))\) 이 됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <bits/stdc++.h>
using namespace std;
#define swap(a,b) (a)^=(b)^=(a)^=(b)
#define endl '\n'
typedef long long lld;
 
priority_queue<pair<intint>vector<pair<intint>>, greater<pair<intint>>> pq;
 
int dijkstra(int start, int endvector<vector<pair<intint>>>& road, vector<vector<int>>& costs)
{
    pq.push({0, start});
    while(!pq.empty())
    {
        int node = pq.top().second, tcost = pq.top().first;
        pq.pop();
        if(costs[start][node] < tcost) continue;
        for(int i=0;i<road[node].size();i++)
        {
            int next = road[node][i].second;
            int tmp = tcost+road[node][i].first;
            if(tmp < costs[start][next])
            {
                costs[start][next] = tmp;
                pq.push({tmp, next});
            }
        }
    }
    return costs[start][end];
}
 
int main()
{
    cin.sync_with_stdio(NULL);
    cin.tie(NULL);
    cout.tie(NULL);
    
    int n, m, x;
    cin >> n >> m >> x;
    vector<vector<pair<intint>>> road(n+1vector<pair<intint>>());
    int start, end, cost;
    for(int i=0;i<m;i++)
    {
        cin >> start >> end >> cost;
        road[start].push_back({cost, end});
    }
    vector<vector<int>> costs(n+1vector<int>(n+199999999));
    for(int i=1;i<=n;i++)
        costs[i][i] = 0;
    dijkstra(x, 0, road, costs);
 
    int mx = 0;
    for(int i=1;i<=n;i++)
    {
        if(i == x) continue;
        costs[x][i] += dijkstra(i, x, road, costs);
        mx = max(mx, costs[x][i]);
    }
    cout << mx;
 
    return 0;
}
cs
728x90

'Problem Solving > BOJ 문제풀이' 카테고리의 다른 글

11404 플로이드  (0) 2021.05.14
11660 구간 합 구하기 5  (0) 2021.05.14
4779 칸토어 집합  (0) 2021.05.05
6064 카잉 달력  (0) 2021.04.29
1202 보석 도둑  (0) 2021.04.27