반응형

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

 

20007번: 떡 돌리기

첫째줄에 N, M, X, Y가 공백으로 구분되어 입력된다. (2 ≤ N ≤ 1,000, 1 ≤ M ≤ 100,000, 1 ≤ X ≤ 10,000,000, 0 ≤ Y < N) 두번째 줄부터 M+1번째 줄까지 A와 B 그리고 A집과 B집 사이의 도로의 길이 C가 주

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. 이어진 집들을 입력받고, vector<pair<int, int>> list[ 1000 ]에 저장하고, visited[ 1000 ] 배열을 만들어 거리를 저장합니다.

 

2. 데이크스트라를 이용하여, Y부터 각 집까지의 거리를 visited 배열에 저장합니다.

 

3. visited 배열을 오름차순으로 정렬하고, for문을 통해 돌면서 거리 * 2의 값을 더해주면서 X를 넘으면 ans++를 해줍니다.

 

4. 이때, 거리 * 2의 값이 X보다 크다면 -1을 출력하고, 그렇지 않다면 ans + 1을 출력합니다.

 

[ 소스코드 ]

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
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
 
using namespace std;
 
int N, M, X, Y;
vector<pair<intint>> list[1000];
int visited[1000];
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> N >> M >> X >> Y;
 
    fill(visited, visited + N, -1);
 
    for (int i = 0; i < M; i++) {
        int A, B, C;
        cin >> A >> B >> C;
 
        list[A].push_back({ B,C });
        list[B].push_back({ A,C });
    }
 
    priority_queue<pair<intint>> pq;
 
    pq.push({ 0,Y });
 
    while (!pq.empty()) {
        const int cur = pq.top().second;
        const int cost = pq.top().first;
        pq.pop();
 
        if (visited[cur] == -1 || visited[cur] >= cost) {
            visited[cur] = cost;
        }
 
        for (auto& next : list[cur]) {
            int nextCost = next.second;
            int nextNode = next.first;
 
            if (visited[nextNode] == -1 || visited[nextNode] > cost + nextCost) {
                visited[nextNode] = cost + nextCost;
                pq.push({ cost + nextCost,nextNode });
            }
        }
    }
 
    sort(visited, visited + N);
 
    int cur = 0;
    int ans = 0;
 
    for (int i = 0; i < N; i++) {
        if (visited[i] * 2 > X) {
            cout << -1;
            return 0;
        }
        
        cur += visited[i] * 2;
 
        if (cur > X) {
            ans++;
            cur = visited[i] * 2;
        }
    }
 
    cout << ans + 1;
}
cs
반응형

+ Recent posts