[๋ฐฑ์ค€] 1054๋ฒˆ: ํŠน์ •ํ•œ ์ตœ๋‹จ ๊ฒฝ๋กœ

2020. 12. 21. 15:33ใ†๐Ÿ‘จ๐Ÿป‍๐Ÿซ ํ”„๋กœ๊ทธ๋ž˜๋ฐ/BOJ(๋ฐฑ์ค€)

 

๋ฐฉํ–ฅ์„ฑ์ด ์—†๋Š” ๊ทธ๋ž˜ํ”„์—์„œ 1๋ฒˆ ์ •์ ์—์„œ N๋ฒˆ ์ •์ ์œผ๋กœ ๊ฐ€๋˜ ๋ฐ˜๋“œ์‹œ V1,V2 ์ •์ ์„ ์ง€๋‚˜๋Š” ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์˜€์Šต๋‹ˆ๋‹ค.์ถœ๋ฐœ ์ง€์ ๊ณผ ๋„์ฐฉ์ง€์ ์€ 1๋ฒˆ ์ •์ ๊ณผ N๋ฒˆ ์ •์ ์œผ๋กœ ๊ณ ์ •๋˜์–ด ์žˆ์œผ๋ฏ€๋กœ

 

1 - V1 - V2 - N

1 - V2 - V1 - N

 

์ด ๋‘ ๊ฐ€์ง€ ๊ฒฝ์šฐ๋งŒ ์ฒดํฌํ•˜๋ฉด ๋ฌธ์ œ์—์„œ ์š”๊ตฌํ•˜๋Š” ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

์ •์ ๊ณผ ๊ฐ„์„ ์˜ ์ตœ๋Œ€ ๊ฐœ์ˆ˜๋ฅผ ๊ฐ์•ˆํ•˜์—ฌ ์‹œ๊ฐ„ ๋ณต์žก๋„ O(|V|*log|E|)์ธ ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.

 

๊ทธ๋ž˜ํ”„๋Š” ์ด์ค‘๋ฒกํ„ฐ๋ฅผ ์‚ฌ์šฉํ•ด ์ธ์ ‘๋ฆฌ์ŠคํŠธ ํ˜•ํƒœ๋กœ ๊ตฌํ˜„ํ–ˆ๊ณ  

 

์ตœ๋‹จ๊ฑฐ๋ฆฌ์˜ ํ•ฉ์ด ๊ฐ€๋Šฅํ•œ ์ตœ๋Œ€๊ฐ’์„ ๋„˜๊ฑฐ๋‚˜ INF์˜ ํ•ฉ์œผ๋กœ ์ธํ•ด ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ ๋  ๊ฒฝ์šฐ๋ฅผ ์ƒ๊ฐํ•˜์—ฌ ์กฐ๊ฑด๋ฌธ์„ ์ž‘์„ฑํ–ˆ์Šต๋‹ˆ๋‹ค.

#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;

const int MAX=800 + 1;
const int INF=987654321;

int N,E,v1,v2,dist[MAX],ans;

vector<vector<pii>> adj_list;

int djikstra(int s,int e){

	fill(dist,dist+N+1,INF);
	dist[s]=0;
    
	priority_queue<pii,vector<pii>,greater<pii>> pq;
	pq.push({0,s});
    
	while(!pq.empty()){
		int cur_node=pq.top().second;
		int cost=pq.top().first;
		pq.pop();
		if(dist[cur_node]<cost) continue;
        
		for(int i=0;i<adj_list[cur_node].size();i++){
			int next_node=adj_list[cur_node][i].second;
			int tmp_cost=cost+adj_list[cur_node][i].first;

			if(tmp_cost<dist[next_node]){
				dist[next_node]=tmp_cost;
				pq.push({tmp_cost,next_node});
			}
		}
	}
    
	return dist[e];
}


int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
    
	cin>>N>>E;
    
	adj_list.resize(N+1);
    
	for(int i=0;i<E;i++){
		int a,b,c;
		cin>>a>>b>>c;
		adj_list[a].push_back({c,b});
		adj_list[b].push_back({c,a});
	}
   
	cin>>v1>>v2;
    
	ans=min(djikstra(1,v1)+djikstra(v1,v2)+djikstra(v2,N),djikstra(1,v2)+djikstra(v2,v1)+djikstra(v1,N));
	
    cout<<(ans>3*800*1000||ans<0?-1:ans)<<"\n";
	
	return 0;
}

๋ถ€์กฑํ•œ ๋ถ€๋ถ„, ๊ถ๊ธˆํ•œ ์  ์–ธ์ œ๋“  ๋Œ“๊ธ€ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค!