알고리즘 문제 해결/BOJ

[다익스트라] BOJ 10282 해킹 (C++)

jmkimmessi 2022. 6. 23. 06:28
반응형

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

 

10282번: 해킹

최흉최악의 해커 yum3이 네트워크 시설의 한 컴퓨터를 해킹했다! 이제 서로에 의존하는 컴퓨터들은 점차 하나둘 전염되기 시작한다. 어떤 컴퓨터 a가 다른 컴퓨터 b에 의존한다면, b가 감염되면

www.acmicpc.net

 

문제 해결 알고리즘

 

문제에 나온 조건을 응용한 다익스트라 알고리즘 문제이다.

 

아래의 링크에 다익스트라 알고리즘에 대해 설명되어있다.

 

https://kimmessi.tistory.com/185?category=871925 

 

[알고리즘] 다익스트라 - 선형 탐색, 우선순위 큐

다익스트라 알고리즘 (Dijkstra's algorithm) 특정 노드에서 출발해 다른 모든 노드로 가는 최단 경로를 구해주는 알고리즘 다익스트라 알고리즘은 음의 간선이 있는 그래프에서는 사용이 불가능하

kimmessi.tistory.com

 

소스 코드

 

#include <bits/stdc++.h>
using namespace std;

const int INF = 1e9;

int d[10002];
vector<pair<int, int>> graph[10002];
int n, d1, c;

void dijkstra(){

    priority_queue<pair<int, int>> pq;

    pq.push({0, c});
    d[c] = 0;

    while(!pq.empty()){

        int now = pq.top().second;
        int dist = -pq.top().first;

        pq.pop();

        if(d[now] < dist) continue;

        for(int i=0;i<graph[now].size();i++){
            int cost = d[now] + graph[now][i].first;

            if(cost < d[graph[now][i].second]){
                d[graph[now][i].second] = cost;
                pq.push({-cost, graph[now][i].second});
            }

        }

    }
}

int main(){

    ios::sync_with_stdio(0);
	cin.tie(0);

    int testCase; cin >> testCase;

    while(testCase--){
        int result_cnt = 0, result_time = 0; 
        cin >> n >> d1 >> c;

        for(int i=0;i<d1;i++){
            int a, b, s; 
            cin >> a >> b >> s;

            graph[b].push_back({s, a});    
        }

        fill(d, d+10001, INF);

        dijkstra();

        for(int i=1;i<=n;i++){
            if(d[i] != INF) {
                result_cnt++;
                result_time = max(result_time, d[i]);
            }

            graph[i].clear();
        } 

        cout << result_cnt << ' ' << result_time << '\n';
        
    }
}
반응형