結果

問題 No.160 最短経路のうち辞書順最小
ユーザー masamasa
提出日時 2016-07-21 16:22:10
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
TLE  
実行時間 -
コード長 1,593 bytes
コンパイル時間 974 ms
コンパイル使用メモリ 91,300 KB
実行使用メモリ 10,524 KB
最終ジャッジ日時 2024-04-23 20:22:45
合計ジャッジ時間 10,905 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
6,816 KB
testcase_01 AC 1 ms
6,944 KB
testcase_02 AC 1 ms
6,940 KB
testcase_03 AC 1 ms
6,940 KB
testcase_04 AC 6 ms
6,940 KB
testcase_05 AC 9 ms
6,940 KB
testcase_06 AC 12 ms
6,944 KB
testcase_07 AC 4 ms
6,944 KB
testcase_08 AC 71 ms
6,944 KB
testcase_09 AC 10 ms
6,944 KB
testcase_10 AC 3,237 ms
6,940 KB
testcase_11 TLE -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
testcase_24 -- -
testcase_25 -- -
testcase_26 -- -
testcase_27 -- -
testcase_28 -- -
testcase_29 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <utility>
#include <queue>
#include <list>

using namespace std;

const int INF = 1e7;

vector<vector<int>> dist_matrix;
vector<vector<int>> connect;
vector<int> distances;

void dijkstra(int start, int goal) {
	distances.assign(dist_matrix.size(), INF);
	distances[start] = 0;

	priority_queue<pair<int, int>> que;
	que.push(make_pair(0, start));
	while (!que.empty()) {
		auto p = que.top();
		int now_dist = p.first;
		int from = p.second;
		que.pop();

		for (auto to : connect[from]) {
			int d = now_dist + dist_matrix[from][to];
			if (d < distances[to]) {
				distances[to] = d;
				que.push(make_pair(d, to));
			}
		}
	}
}

bool dfs(list<int> &route, int goal) {
	int now = route.back();

	for (auto to : connect[now]) {
		if (distances[now] + dist_matrix[now][to] == distances[to]) {
			route.emplace_back(to);
			if (to == goal) {
				return true;
			}
			if (dfs(route, goal)) {
				return true;
			}
			route.pop_back();
		}
	}
	return false;
}

int main() {
	int n, m, s, g, a, b, c;

	cin >> n >> m >> s >> g;
	dist_matrix.assign(n, vector<int>(n, INF));
	connect.assign(n, vector<int>());

	for (int i = 0; i < m; i++) {
		cin >> a >> b >> c;
		dist_matrix[a][b] = c;
		dist_matrix[b][a] = c;
		connect[a].emplace_back(b);
		connect[b].emplace_back(a);
	}
	for (auto &v : connect) {
		sort(v.begin(), v.end());
	}

	dijkstra(s, g);
	list<int> route = {s};
	dfs(route, g);

	for (auto x : route) {
		cout << x;
		if (x != g) {
			cout << " ";
		} else {
			cout << endl;
		}
	}
	return 0;
}
0