3364. 吉吉木坐地铁

煤渣2333

dfs+剪枝

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>

using namespace std;

const int maxn = (int)1e5 + 5, inf = 999999999;
vector<int> g[maxn];
bool visited[maxn];
int ans = inf;
int n, q, s, d;

void dfs(int v, int depth) {
    if (v == d)
        ans = min(depth, ans);
    else {
        for (int w : g[v]) {
            if (!visited[w]) {
                visited[w] = true;
                dfs(w, depth + 1);
                visited[w] = false;
            }
        }
    }
}

int main() {
    cin >> n >> q;
    for (int i = 0; i < n; i++) {
        int u, v;
        scanf("%d %d", &u, &v);
        g[u].push_back(v);
        g[v].push_back(u);
    }
    while (q--) {
        ans = inf;
        scanf("%d %d", &s, &d);
        visited[s] = true;
        dfs(s, 0);
        visited[s] = false;
        if (ans != inf) printf("%d\n", ans);
        else printf("-1\n");
    }
    return 0;
}
你当前正在回复 博客/题目
存在问题!