티스토리 뷰

다익스트라를 이용하며 최단거리로 지나가는 경로를 저장해 매번 확인했다

https://sejinik.tistory.com/131와 비슷한 방법이다!

 

사실 이렇게 풀면 되긴하지만 시간이 조금 오래걸린다

다른 사람들 풀이를 보니 여러가지 최적화가 있는 것 같다

 

내가 푼 방법은 Passed라는 배열에 지나가는 경로를 저장하고

매번 다익스트라를 돌고 확인하는 하라는대로 하는 방법이다

 

소스코드

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 <algorithm>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
int T,n,m,t,s,g,h;
int d[2020];
vector<vector<pair<int,int>>> Graph;
vector<vector<int>> Passed;
vector<int>ans;
 
bool f(int u,int v){
    if(u==-1return false;
    if((u==g&&v==h) || (u==h&&v==g)) return true;
    for(int i=0;i<Passed[u].size();i++) {
       if(f(Passed[u][i],u)) return true;
    }
    return false;
}
void dijk(int to){
    memset(d,-1,sizeof(d));
    priority_queue<pair<pair<int,int>,int>> pq;
    pq.push({{0,s},-1});
    while(!pq.empty()){
        int pos = pq.top().first.second;
        int cost = -pq.top().first.first;
        int pre = pq.top().second;
        pq.pop();
 
        if(d[pos]==cost) Passed[pos].push_back(pre);
        if(d[pos] != -1continue;
        d[pos]=cost;
        Passed[pos].push_back(pre);
        for(int i=0;i<Graph[pos].size();i++){
            int next = Graph[pos][i].first;
            int ncost = -cost - Graph[pos][i].second;
            if(d[next]==-1pq.push({{ncost,next},pos});
        }
    }
    if(d[to]==-1return;
    for(int i=0;i<Passed[to].size();i++){
        if(f(Passed[to][i],to)) {
            ans.push_back(to); return;
        }
    }
}
int main(){
    //freopen("input.txt","r",stdin);
    scanf(" %d",&T);
    while(T--){
        Graph.clear();
        scanf(" %d %d %d",&n,&m,&t);
        Graph.resize(n);
        scanf("%d %d %d",&s,&g,&h);
        s--;g--;h--;
        for(int i=0;i<m;i++){
            int u,v,c; scanf(" %d %d %d",&u,&v,&c);
            u--; v--;
            Graph[u].push_back({v,c});
            Graph[v].push_back({u,c});
        }
        ans.clear();
        for(int i=0;i<t;i++){
            int e; scanf(" %d",&e); e--;
            dijk(e);
        }
        sort(ans.begin(),ans.end());
        for(int i=0;i<ans.size();i++printf("%d ",ans[i]+1);
        puts("");
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

'알고리즘 > BOJ' 카테고리의 다른 글

[백준] 1781 컵라면  (0) 2019.08.27
[백준] 15903 카드 합체 놀이  (0) 2019.08.27
[백준] 5719 거의 최단 경로  (0) 2019.08.27
[백준] 17267 상남자  (0) 2019.08.27
[백준] 1987 알파벳  (0) 2019.08.27
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
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
글 보관함