알고리즘
백준 1956번 운동 C++
영춘권의달인
2022. 11. 11. 12:51
https://www.acmicpc.net/problem/1956
1956번: 운동
첫째 줄에 V와 E가 빈칸을 사이에 두고 주어진다. (2 ≤ V ≤ 400, 0 ≤ E ≤ V(V-1)) 다음 E개의 줄에는 각각 세 개의 정수 a, b, c가 주어진다. a번 마을에서 b번 마을로 가는 거리가 c인 도로가 있다는 의
www.acmicpc.net
플로이드-워셜
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
int v, e;
vector<vector<int>> graph;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> v >> e;
graph = vector<vector<int>>(v + 1, vector<int>(v + 1, -1));
for (int i = 0; i < e; i++) {
int a, b, c;
cin >> a >> b >> c;
graph[a][b] = c;
}
for (int k = 1; k <= v; k++) {
for (int i = 1; i <= v; i++) {
for (int j = 1; j <= v; j++) {
if (graph[i][k] == -1) continue;
if (graph[k][j] == -1) continue;
if (graph[i][j] == -1) graph[i][j] = graph[i][k] + graph[k][j];
else graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j]);
}
}
}
bool ans = false;
int dist = 987654321;
for (int i = 1; i <= v; i++) {
if (graph[i][i] == -1) continue;
ans = true;
dist = min(dist, graph[i][i]);
}
if (ans) cout << dist;
else cout << -1;
}