티스토리 뷰
https://www.acmicpc.net/problem/1504
1504번: 특정한 최단 경로
첫째 줄에 정점의 개수 N과 간선의 개수 E가 주어진다. (2 ≤ N ≤ 800, 0 ≤ E ≤ 200,000) 둘째 줄부터 E개의 줄에 걸쳐서 세 개의 정수 a, b, c가 주어지는데, a번 정점에서 b번 정점까지 양방향 길이 존
www.acmicpc.net
플로이드 와샬 알고리즘을 이용해 풀이했습니다.
C++ 소스 코드
#include <iostream>
#define MAX 801
using namespace std;
int n,e,dist[MAX][MAX];
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> n >> e;
int a,b,c,v1,v2;
fill(&dist[0][0],&dist[n][n]+1,-1);
for(int i=0;i<=n;i++){
dist[i][i] = 0;
}
for(int i=0;i<e;i++){
cin >> a >> b >> c;
dist[a][b] = c;
dist[b][a] = c;
}
cin >> v1 >> v2;
for(int k=1;k<=n;k++){
for(int i=1;i<=n;i++){
if(dist[i][k] == -1) continue;
for(int j=1;j<=n;j++){
if(dist[k][j]==-1) continue;
if(dist[i][j]== -1 || dist[i][j] > dist[i][k]+dist[k][j]){
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
int ans = -1;
if(dist[1][v1] != -1 && dist[v1][v2] != -1 && dist[v2][n] != -1){
// 1 -> v1 -> v2 -> n
ans = dist[1][v1]+dist[v1][v2]+dist[v2][n];
}
if(dist[1][v2] != -1 && dist[v2][v1] != -1 && dist[v1][n] != -1){
// 1 -> v2 -> v1 -> n
int tmp = dist[1][v2]+dist[v2][v1]+dist[v1][n];
if(ans == -1 || ans > tmp){
ans = tmp;
}
}
cout << ans << '\n';
return 0;
}
'Algorithm > 알고리즘 문제풀이' 카테고리의 다른 글
BOJ) 1766 - 문제집 (0) | 2020.11.11 |
---|---|
BOJ) 2636 - 치즈 (0) | 2020.11.11 |
BOJ) 2589 - 보물섬 (0) | 2020.11.06 |
프로그래머스) Lv2 - 쿼드압축 후 개수 세기 (0) | 2020.10.30 |
BOJ) 10451 - 순열 사이클 (0) | 2020.10.22 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- ios
- 안드로이드
- Lottie
- SWEA
- Swift weak
- blendshape
- ARKit
- 백준온라인저지
- boj
- 카카오인턴십
- DispatchQueue
- cocoapods
- rxswift6
- infallible
- Kotlin
- disposeBag
- 코코아팟
- UIHostingController
- 알고리즘
- blendshapes
- Swift
- 프로그래머스
- GraphDB
- 백준
- Swift unowned
- SwiftUI
- Reactivex
- coreml
- C++
- rxswift
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함