YeJin's Footsteps

1238번: 파티 본문

Computer Science & Engineering/알고리즘

1238번: 파티

YeJinii 2021. 7. 20. 23:28

문제 링크

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

 

1238번: 파티

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

www.acmicpc.net

문제 풀이 코드

#include <iostream>
#include <vector>
#include <queue>
#include <functional>

using namespace std;
using P = pair<int,int>;

const int MN=1010;
const int INF=1e9;

vector <P> graph [MN];
int Dist[MN];
int Answer[MN];

void Dijkstra(int S){
    
    priority_queue<P, vector<P>, greater<P>> pq;
    
    Dist[S]=0;
    pq.push({0,S});

    while(!pq.empty()){
        P cur = pq.top(); pq.pop();
        int w=cur.first;
        int v=cur.second;
        
        if(Dist[v] < w) continue;

        for(int j=0; j<graph[v].size(); j++){
            int next=graph[v][j].first;
            int cost=graph[v][j].second;

            if(Dist[next]>w+cost){
                Dist[next]=w+cost;
                pq.push({Dist[next],next});
            }
        }
    }
} 

int main(void){
    
    int N, M, X; cin>>N>>M>>X;
    
    for(int i=0; i<M; i++){
        int u,v,w; cin>>u>>v>>w;
        graph[u].push_back({v,w});
    }


    //모든 정점에서 X까지 가는 최단 경로를 구함
    for(int i=1; i<=N; i++){
        fill(Dist,Dist+N+1,INF);
        Dijkstra(i);
        Answer[i]=Dist[X];
    }

    fill(Dist,Dist+N+1,INF);
    Dijkstra(X);
    for(int i=1; i<=N; i++){
        Answer[i]+=Dist[i];
    }

    int MAX=-INF;

    for(int i=1; i<=N; i++){
        MAX=max(MAX,Answer[i]);
    }

    cout<<MAX;

    return 0;
}

graph 백터와 우선순위 큐에 가중치와 연결 정점을 저장하는 순서가 달라서 답이 바로 나오지 않았다.

다익스트라를 오는길 가는길 두번 구하는 문제다.

'Computer Science & Engineering > 알고리즘' 카테고리의 다른 글

로또의 최고 순위와 최저 순위  (0) 2021.07.30
9370번: 미확인 도착지  (0) 2021.07.21
2458번: 키 순서  (0) 2021.07.19
11404번: 플로이드  (0) 2021.07.19
11403번: 경로 찾기  (0) 2021.07.19
Comments