Notice
Recent Posts
Recent Comments
Link
알고리즘 모음(C++)
백준 22865 - 가장 먼 곳(C++) 본문
문제 링크입니다. https://www.acmicpc.net/problem/22865
22865번: 가장 먼 곳
$N$개의 땅 중에서 한 곳에 자취를 하려고 집을 알아보고 있다. 세 명의 친구 $A$, $B$, $C$가 있는데 이 친구들이 살고 있는 집으로부터 가장 먼 곳에 집을 구하려고 한다. 이때, 가장 먼 곳은 선택할
www.acmicpc.net
다익스트라를 이용하는 문제입니다.
![](https://blog.kakaocdn.net/dn/bhgyvJ/btsBbIDkcXq/uGxNCgvSFSgM9StpjhKvhK/img.jpg)
![](https://blog.kakaocdn.net/dn/ycKhK/btsA9OKCtdO/7ys01cZEfuWszIxMSYGPkK/img.jpg)
1 ~ N까지 중에서, 친구의 위치가 3개가 주어질 때, 최소 거리가 가장 긴 위치를 찾는 문제입니다.
1부터 시작해 1->1 ~ 1->N,,,,,,N->1 ~ N->N까지 모든 경우를 구한 뒤,
3지점까자의 각각의 거리를 비교해서 최솟값을 찾는 것은 다익스트라를 100,000번 돌려야 되기 때문에 시간초과가 생기게 됩니다.
따라서, 다른 방법으로 3개의 친구 위치에서 다익스트라를 통해 1~N까지의 거리를 구한 뒤, 이를 비교해주면
다익스트라를 3번만 돌리면 되기에 훨씬 시간이 줄어들게 됩니다.
자세한 것은 코드를 참고해주세요.
#define _CRT_SECURE_NO_WARNINGS
#include <cstring>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
#include <cmath>
#include <cstdio>
#include <string>
#define INF 98765432100
#define LL long long
#define F first
#define S second
using namespace std;
int N, M;
int Friend[3];
LL Distance[100001][3];
vector<pair<int, int>> connect[100001];
priority_queue<pair<LL, int>, vector<pair<LL, int>>> q;
LL Min(LL x, LL y, LL z){
LL mini = min(x, y);
mini = min(mini, z);
return mini;
}
void reset_distance(int num){
for(int i = 1; i <= N; i++) Distance[i][num] = INF;
}
void Dijstra(int st, int num){
reset_distance(num);
Distance[st][num] = 0;
q.push({-Distance[st][num], st});
while(!q.empty()){
int x = q.top().S;
LL cost = -q.top().F;
q.pop();
if(Distance[x][num] < cost) continue;
for(int i = 0; i < connect[x].size(); i++){
int xx = connect[x][i].F;
LL n_cost = cost + connect[x][i].S;
if(Distance[xx][num] > n_cost){
Distance[xx][num] = n_cost;
q.push({-Distance[xx][num], xx});
}
}
}
}
void solve(){
LL mini = -INF;
int Point;
for(int i = 0; i < 3; i++){
Dijstra(Friend[i], i);
}
for(int i = 1; i <= N; i++){
LL Dis = Min(Distance[i][0], Distance[i][1], Distance[i][2]);
if(mini < Dis){
mini = Dis;
Point = i;
}
}
cout << Point;
}
int main() {
cin.tie(0);
cout.tie(0);
cin >> N;
for(int i = 0; i < 3; i++) cin >> Friend[i];
cin >> M;
for(int i = 1; i <= M; i++){
int x, y, cost;
cin >> x >> y >> cost;
connect[x].push_back({y, cost});
connect[y].push_back({x, cost});
}
solve();
return 0;
}
![](https://blog.kakaocdn.net/dn/dbVGd1/btsBccLb3AT/VzIpnslTdCrelKFGkkJNQK/img.jpg)
질문 및 조언은 댓글 남겨주세요.
'백준' 카테고리의 다른 글
백준 17270 - 연예인은 힘들어(C++) (2) | 2023.12.03 |
---|---|
백준 23801 - 두 단계 최단 경로 2(C++) (0) | 2023.12.01 |
백준 20007 - 떡 돌리기(C++) (1) | 2023.11.27 |
백준 23793 - 두 단계 최단 경로 1(C++) (1) | 2023.11.24 |
백준 18223 - 민준이와 마산 그리고 건우(C++) (3) | 2023.11.22 |