본문 바로가기
  • Let's study
PS/백준

[C++] 백준 1238: 파티

by 코딩고수이고파 2023. 10. 4.

문제

https://www.acmicpc.net/problem/1238

 

1238번: 파티

첫째 줄에 N(1 ≤ N ≤ 1,000), M(1 ≤ M ≤ 10,000), X가 공백으로 구분되어 입력된다. 두 번째 줄부터 M+1번째 줄까지 i번째 도로의 시작점, 끝점, 그리고 이 도로를 지나는데 필요한 소요시간 Ti가 들어

www.acmicpc.net

 

해결방법

다익스트라 알고리즘으로 풀 수 있다.

  1. 1부터 N까지 각 노드를 출발지로 하는 최단거리를 구한 후, X를 목적지로 하는 최단 거리를 배열에 저장한다.
  2. X를 출발지로 하고 1부터 N까지의 최단 거리를 구한 후, 1에서 구한 배열에 더해준다.
  3. 배열에 각 인덱스에 저장된 값은 노드 ->  X + X -> 노드 값이다. 따라서 가장 큰 값을 출력해주면 된다.

 

코드

#include<iostream>
#include<vector>
#include<queue>
#define INF 1e9 

using namespace std;

int n, m, x;
vector<pair<int, int>>graph[1001];
int d[1001];
int reverse_d[1001];

void dijkstra(int start) {
	fill_n(d, 1001, INF);
	priority_queue<pair<int, int>>pq;

	pq.push({ 0,start });
	d[start] = 0;

	while (!pq.empty()) {
		int dist = -pq.top().first;
		int now = pq.top().second;
		pq.pop();

		if (d[now] < dist)
			continue;

		for (int i = 0; i < graph[now].size(); i++) {
			int cost = dist + graph[now][i].second;

			if (cost < d[graph[now][i].first]) {
				d[graph[now][i].first] = cost;
				pq.push({ -cost,graph[now][i].first });
			}
		}
	}
}

int main(){
	ios_base::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);

	cin >> n >> m >> x;

	for (int i = 0; i < m; i++) {
		int a, b, t;
		cin >> a >> b >> t;
		graph[a].push_back({ b,t });
	}

	for (int i = 1; i <= n; i++) {
		dijkstra(i);

		reverse_d[i] = d[x];
	}

	dijkstra(x);

	int max = 0;
	for (int i = 1; i <= n; i++) {
		reverse_d[i] += d[i];
		if (reverse_d[i] > max)
			max = reverse_d[i];
	}

	cout << max;

	return 0;
}

'PS > 백준' 카테고리의 다른 글

[C++] 백준 1520: 내리막길  (0) 2023.10.08
[C++] 백준 19637: IF문 좀 대신 써줘  (1) 2023.10.06
[C++] 백준 25828: Corona Virus Testing  (0) 2023.05.22
[C++] 백준 25881: Electric Bill  (0) 2023.05.21
[C++] 백준 9772: Quadrants  (0) 2023.05.20

댓글