結果

問題 No.160 最短経路のうち辞書順最小
ユーザー tkzw_21
提出日時 2015-03-02 13:50:28
言語 C++11(廃止可能性あり)
(gcc 13.3.0)
結果
AC  
実行時間 16 ms / 5,000 ms
コード長 1,515 bytes
コンパイル時間 1,936 ms
コンパイル使用メモリ 174,616 KB
実行使用メモリ 6,944 KB
最終ジャッジ日時 2024-06-24 01:10:44
合計ジャッジ時間 2,665 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

typedef pair<int,int> P;
typedef pair<int,pair<int,int>> PP;
typedef long long ll;

const double EPS = 1e-8;
const int INF = 1e9;
const int MOD = 1e9+7;

int dy[] = {0,1,0,-1};
int dx[] = {1,0,-1,0};

struct edge{
	int to,cost;
	bool operator<(const edge &e)const{return to < e.to;}
	bool operator==(const edge &e)const{return to == e.to;}
};

vector<int> dijkstra(int s,int g,vector<vector<edge>>&es){
	priority_queue<pair<int,int>,vector<P>,greater<P>> pq;
	vector<int> dist(es.size(),INF);
	
	pq.push(make_pair(0,s));
	dist[s] = 0;
	
	while(!pq.empty()){
		pair<int,int> p = pq.top();pq.pop();
		int u = p.second,d = p.first;
		for(int i=0;i<es[u].size();i++){
			int  v = es[u][i].to,c = es[u][i].cost;
			if(dist[v] == INF || dist[v] > dist[u] + c){
				dist[v] = d + c;
				pq.push(make_pair(d+c,v));
			}
		}
	}

	vector<int> path;
	path.push_back(g);
	int u = g;
	while(s != u){
		for(int i=0;i<es[u].size();i++){
			int v = es[u][i].to,c = es[u][i].cost;
			if(dist[u] - dist[v] == c){
				path.push_back(v);
				u = v;
				break;
			}
		}
	}
	return path;
}



int main(void) {
	int n,m,s,g;
	cin >> n >> m >> s >> g;
	vector<vector<edge>> es(n);

	for(int i=0;i<m;i++){
		int a,b,c;
		cin >> a >> b >> c;
		es[a].push_back(edge{b,c});
		es[b].push_back(edge{a,c});
	}
	for(int i=0;i<n;i++){
		sort(es[i].begin(),es[i].end());
	}
	vector<int> path = dijkstra(g,s,es);
	for(int i=0;i<path.size();i++){
		cout << path[i]<< " ";
	}
	cout << endl;

	return 0;
}
0