Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 백준 17471
- 시간 복잡도
- 버킷 정렬
- 해시구현
- 백준
- 게리멘더링2
- 백준 5397
- 구현
- 해시 구현
- ㅣ풀이
- qorwns
- 백준 17822
- 백준 2447
- dfs
- 조세퍼스 순열
- 별 찍기 10
- 백준 17779
- 5397
- Stack 이란
- C/C++ 구현
- 자료구조
- 풀이
- heap
- 백준 1406
- 백준 1158
- 1764
- c#
- 스택의 특징
- AVL 시간 복잡도
- 원판 돌리기
Archives
- Today
- Total
홍시홍의 프로그래밍
[백준 5719] 거의 최단 경로 본문
요구사항
최단 경로를 제외한 나머지 중 최단 경로를 구하여라
풀이
최단 경로를 지우고 나서 최단 경로를 구하면 된다
단순히 다익스트라 문제처럼 보이지만 최단 경로를 지우는 구현, 아이디어가 힘든거 같다
1. 최단 경로 구한다
2. 최단 경로로 이어진 경로 삭제
- 도착점부터 시작점까지의 최단 경로를 저장하는 경로가 있어야 한다.
- 다익스트라 알고리즘을 구현할때, 새로운 dist로 갱신이 되면 그 경로가 end로 가기위한 경로중 하나이다.
- 제일 끝점에서 부터 start까지 역순으로 탐색하여 최단 경로의 길이를 -1로 초기화 시켜준다
3. 거의 최단 경로 구하기
#include <iostream>
#include <cstdio>
#include <limits.h>
#include <memory.h>
#include <vector>
#include <queue>
using namespace std;
int n,m;
int startnode, endnode;
vector<pair<int,int>> graph[550];
vector<pair<int,int>> Minnode[550];
int dist[550];
void Getdistance(){
//거리 초기화
for(int i=0 ; i <n;i++) dist[i]=987654321;
dist[startnode]=0;
priority_queue<pair<int,int>, vector<pair<int,int>> , greater<> > q;
q.push({0,startnode});
while(!q.empty()){
int nownode= q.top().second;
int nowdist = q.top().first;
q.pop();
for(int i=0 ; i <graph[nownode].size() ; i++){
int nextnode = graph[nownode][i].first;
int nextdist = graph[nownode][i].second;
if(nextdist ==-1) continue;
if(dist[nextnode] > nowdist + nextdist){
dist[nextnode] = nowdist + nextdist;
q.push({dist[nextnode],nextnode});
Minnode[nextnode].clear();
Minnode[nextnode].push_back({nownode,dist[nextnode]});
}
else if(dist[nextnode] == nowdist + nextdist){
Minnode[nextnode].push_back({nownode,dist[nextnode]});
}
}
}
}
int main()
{
while(true){
scanf("%d%d%d%d",&n,&m,&startnode,&endnode);
if(n==0 && m==0) break;
//입력 받기
for(int i=0 ; i < n ; i++){
graph[i].clear();
Minnode[i].clear();
}
for(int i=0 ; i < m ; i++){
int x, y,z;
scanf("%d%d%d",&x,&y,&z);
graph[x].push_back({y,z});
}
//최단 경로 구하기
Getdistance();
//최단 경로길 제거
queue<int> que;
que.push(endnode);
while(!que.empty()){
int now = que.front();
que.pop();
for(int i=0 ; i <Minnode[now].size();i++){
int next = Minnode[now][i].first;
for(int j=0; j< graph[next].size();j++){
if(graph[next][j].first == now){
graph[next][j].second=-1;
}
}
que.push(next);
}
}
//거의 최단 경로 구하기
Getdistance();
if(dist[endnode]==987654321) cout<<-1<<endl;
else cout<< dist[endnode]<<endl;
}
}
'알고리즘 문제풀이 > 백준' 카테고리의 다른 글
[백준 1463] 1로 만들기 (0) | 2020.03.16 |
---|---|
[백준 9370] 미확인 도착지 (0) | 2020.03.16 |
[백준 1072] 게임 (0) | 2020.03.14 |
[백준 7453] 합이 0인 네 정수 (0) | 2020.03.14 |
[백준 1300] k번째 수 (0) | 2020.03.14 |
Comments