結果
| 問題 |
No.2565 はじめてのおつかい
|
| コンテスト | |
| ユーザー |
👑 |
| 提出日時 | 2023-10-31 14:41:49 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 106 ms / 2,000 ms |
| コード長 | 1,177 bytes |
| コンパイル時間 | 2,274 ms |
| コンパイル使用メモリ | 204,660 KB |
| 最終ジャッジ日時 | 2025-02-17 17:09:32 |
|
ジャッジサーバーID (参考情報) |
judge4 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 50 |
ソースコード
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll INF = 1ll << 60;
void bfs(int start, vector<vector<int>> &graph, vector<ll> &dists) {
dists[start] = 0;
queue<pair<int, ll>> q;
q.push(pair<int, ll>(start, 0));
while (!q.empty()) {
int now_v = q.front().first;
ll d = q.front().second;
q.pop();
for (int next_v : graph[now_v]) {
if (dists[next_v] < INF) continue;
dists[next_v] = d + 1;
q.push(pair<int, ll>(next_v, d + 1));
}
}
}
int main() {
int N, M;
cin >> N >> M;
vector<vector<int>> graph(N, vector<int>());
for (int i = 0; i < M; i++) {
int u, v;
cin >> u >> v;
u -= 1, v -= 1;
graph[u].push_back(v);
}
vector<ll> dist_0(N, INF);
bfs(0, graph, dist_0);
vector<ll> dist_N_2(N, INF);
bfs(N-2, graph, dist_N_2);
vector<ll> dist_N_1(N, INF);
bfs(N-1, graph, dist_N_1);
ll ans = min(
dist_0[N-2] + dist_N_2[N-1] + dist_N_1[0],
dist_0[N-1] + dist_N_1[N-2] + dist_N_2[0]
);
if (ans < INF) cout << ans << endl;
else cout << -1 << endl;
}