【題解】AtCoder ABC 132E – Hopscotch Addict

【題目敘述】https://atcoder.jp/contests/abc132/tasks/abc132_e

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;

int n, m, a, b, s, t, dis[100005][3];
vector <int> v[100005];

int main() {
    cin >> n >> m;
    for (int i = 0; i < m; i++){
        cin >> a >> b;
        v[a].push_back(b);
    }
    cin >> s >> t;
    memset(dis, -1, sizeof(dis));
    dis[s][0] = 0;
    queue <pair<int, int> > q;
    q.push({s, 0});
    while (!q.empty()){
        int x = q.front().first, y = q.front().second;
        q.pop();
        for (int i:v[x]){
            if (dis[i][(y+1)%3] != -1) continue;
            dis[i][(y+1)%3] = dis[x][y]+1;
            q.push({i, (y+1)%3});
        }
    }
    if (dis[t][0] == -1) cout << -1 << "\n";
    else cout << dis[t][0]/3 << "\n";
}

分享本文 Share with friends