https://www.acmicpc.net/problem/11780
11780번: 플로이드 2
첫째 줄에 도시의 개수 n이 주어지고 둘째 줄에는 버스의 개수 m이 주어진다. 그리고 셋째 줄부터 m+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스의 출발 도시의 번호가
www.acmicpc.net
[난이도] Gold4
[유형] 플로이드 와샬
[풀이]
플로이드 와샬의 경로까지 출력해야 하는 문제이다.
최단경로를 갱신할 때 경유지 i,j의 경유지 k를 path[i][j]에 저장해놓고
이것을 이용해 재귀함수로 경로를 출력한다.
#include <algorithm> #include <cstdio> #include <vector> using namespace std; int N,M,dist[101][101],path[101][101],INF=9e8; void prt(int i,int j,vector<int>& tmp){ if(i==j) { tmp.push_back(i); return; } int p = path[i][j]; prt(i,p,tmp); if(i!=p) prt(p,j,tmp); } int main(){ scanf("%d%d",&N,&M); for(int i=1;i<=N;i++) for(int j=1;j<=N;j++) if(i!=j) dist[i][j]=INF; while(M--){ int a,b,c; scanf("%d%d%d",&a,&b,&c); if(dist[a][b] > c){ dist[a][b] = c; path[a][b] = a; } } for(int k=1;k<=N;k++){ for(int i=1;i<=N;i++){ for(int j=1;j<=N;j++){ if(dist[i][j]>dist[i][k]+dist[k][j]){ dist[i][j]=dist[i][k]+dist[k][j]; path[i][j]=k; } } } } for(int i=1;i<=N;i++){ for(int j=1;j<=N;j++) printf("%d ",dist[i][j]==INF ? 0 : dist[i][j]); puts(""); } for(int i=1;i<=N;i++){ for(int j=1;j<=N;j++){ if(!dist[i][j]) printf("0"); else { vector<int> tmp; prt(i,j,tmp); tmp.push_back(j); printf("%d ",tmp.size()); for(auto k : tmp) printf("%d ",k); } puts(""); } } }
https://github.com/has2/Problem-Solving/blob/master/boj-solved.ac/Gold4/11780.cpp
'Problem-Solving > BOJ' 카테고리의 다른 글
[BOJ/백준][Gold4] 10993 : 별 찍기 - 18 (C++) (0) | 2020.12.30 |
---|---|
[BOJ/백준][Gold4] 7570 : 줄 세우기 (C++) (0) | 2020.12.27 |
[BOJ/백준][Gold4] 2157 : 여행 (C++) (0) | 2020.12.27 |
[BOJ/백준][Gold4] 2306 : 유전자 (C++) (0) | 2020.12.27 |
[BOJ/백준][Gold4] 2109 : 순회강연 (C++) (0) | 2020.12.27 |