結果
問題 | No.2565 はじめてのおつかい |
ユーザー |
|
提出日時 | 2023-12-02 15:56:00 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 153 ms / 2,000 ms |
コード長 | 1,805 bytes |
コンパイル時間 | 2,220 ms |
コンパイル使用メモリ | 198,792 KB |
最終ジャッジ日時 | 2025-02-18 05:02:07 |
ジャッジサーバーID (参考情報) |
judge2 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 50 |
ソースコード
#include <bits/stdc++.h>//#include<atcoder/all>using namespace std;//using namespace atcoder;using ll = long long;const ll INF = 1000000000000000000LL;//const ll mod = 998244353;int n, m, u[100009], v[100009];vector<int>G[100009];ll dist[3][100009];queue<int>Q;int main() {cin >> n >> m;for (int i = 1; i <= m; i++) {cin >> u[i] >> v[i];G[u[i]].push_back(v[i]);}for (int i = 0; i < 3; i++) {for (int j = 1; j <= n; j++)dist[i][j] = -1;}dist[0][1] = 0;Q.push(1);while (!Q.empty()) {int pos = Q.front(); Q.pop();for (int i = 0; i < G[pos].size(); i++) {int nex = G[pos][i];if (dist[0][nex] == -1) {dist[0][nex] = dist[0][pos] + 1;Q.push(nex);}}}dist[1][n - 1] = 0;Q.push(n - 1);while (!Q.empty()) {int pos = Q.front(); Q.pop();for (int i = 0; i < G[pos].size(); i++) {int nex = G[pos][i];if (dist[1][nex] == -1) {dist[1][nex] = dist[1][pos] + 1;Q.push(nex);}}}dist[2][n] = 0;Q.push(n);while (!Q.empty()) {int pos = Q.front(); Q.pop();for (int i = 0; i < G[pos].size(); i++) {int nex = G[pos][i];if (dist[2][nex] == -1) {dist[2][nex] = dist[2][pos] + 1;Q.push(nex);}}}ll ans1 = INF, ans2 = INF, ans3 = INF;if (dist[0][n - 1] != -1 && dist[1][n] != -1 && dist[2][1] != -1) {ans1 = dist[0][n - 1] + dist[1][n] + dist[2][1];}if (dist[0][n] != -1 && dist[2][n-1] != -1 && dist[1][1] != -1) {ans2 = dist[0][n] + dist[2][n-1] + dist[1][1];}if (dist[0][n - 1] != -1 && dist[1][1] != -1 && dist[0][n] != -1&&dist[2][1]!=-1) {ans3 = dist[0][n - 1] + dist[1][1] + dist[0][n]+dist[2][1];}//cout << ans1 << " " << ans2 << " " << ans3 << endl;ll ans = min(ans1, min(ans2, ans3));if (ans != INF)cout << ans << endl;else cout << "-1" << endl;}