반응형

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

 

플로이드 와샬 알고리즘을 이용해 풀고

 

거리의 최대치와 INT StackOverflow를 유의해서 풀어야한다.

 

#include <bits/stdc++.h>
using namespace std;

const int INF = 2e9;
int n,m, dist[401][401];

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	fill(&dist[0][0], &dist[400][401], INF);

	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		int a, b, c;
		cin >> a >> b >> c;
		dist[a][b] = c;
	}

	for (int k = 1; k <= n; k++) {
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= n; j++) {
				if (dist[i][k] >= INF || dist[k][j] >= INF) continue;
				dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
			}
		}
	}

	int ans = INT_MAX;
	for (int i = 1; i <= n; i++) {
		ans = min(dist[i][i], ans);
	}

	if (ans == INF) {
		cout << -1 << '\n';
	}
	else {
		cout << ans << '\n';
	}
	return 0;
}

백준 1956

반응형

+ Recent posts