結果
| 問題 | No.2565 はじめてのおつかい | 
| コンテスト | |
| ユーザー |  umezo | 
| 提出日時 | 2023-12-02 15:58:19 | 
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 67 ms / 2,000 ms | 
| コード長 | 1,315 bytes | 
| コンパイル時間 | 2,173 ms | 
| コンパイル使用メモリ | 205,772 KB | 
| 最終ジャッジ日時 | 2025-02-18 05:04:17 | 
| ジャッジサーバーID (参考情報) | judge1 / judge4 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 3 | 
| other | AC * 50 | 
ソースコード
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define ALL(v) v.begin(), v.end()
typedef long long ll;
#include <bits/stdc++.h>
using namespace std;
const ll INF=1LL<<60;
struct Edge{
  int to;
  ll w;
  Edge(int to,ll w) : to(to),w(w) {}
};
using Graph=vector<vector<Edge>>;
using pli=pair<ll,int>;
template<class T> bool chmin(T& a,T b){
  if(a>b){
    a=b;
    return true;
  }
  return false;
}
Graph G;
vector<ll> dijkstra(int s){
  int n=G.size();
  vector<ll> dist(n,INF);
  dist[s]=0;
  
  priority_queue<pli,vector<pli>,greater<pli>> que;
  que.push({dist[s],s});
  
  while(!que.empty()){
    int v=que.top().second;
    ll d=que.top().first;
    que.pop();
    
    if(d>dist[v]) continue;
    for(auto e:G[v]){
      if(chmin(dist[e.to],dist[v]+e.w)){
        que.push({dist[e.to],e.to});
      }
    }
  }
  return dist;
}
int main(){
  ios::sync_with_stdio(false);
  std::cin.tie(nullptr);
  int n,m;
  cin>>n>>m;
  
  G.resize(n);
  rep(i,m){
    int a,b;
    cin>>a>>b;
    a--,b--;
    G[a].push_back(Edge(b,1));
  }
  
  vector<ll> dis=dijkstra(0);
  vector<ll> dis1=dijkstra(n-2);
  vector<ll> dis2=dijkstra(n-1);
  
  ll mi=INF;
  mi=min(mi,dis[n-2]+dis1[n-1]+dis2[0]);
  mi=min(mi,dis[n-1]+dis2[n-2]+dis1[0]);
  if(mi==INF) cout<<-1<<endl;
  else cout<<mi<<endl;
  
  return 0;
}
            
            
            
        