题解:P12126 [蓝桥杯 2024 省 B 第二场] 狡兔 k 窟

· · 题解

题解:P12126 [蓝桥杯 2024 省 B 第二场] 狡兔 k 窟

Updata 2025/7/24:更正了 bitset 的初始化复杂度。

题目大意:

有一张 n 个节点 n-1 条边的图,每条边的边权为 1,同时 c_{i} 相同的节点可以互相瞬间到达。问每个 s \to t 的最短路径。

解题思路:

我们可以把所有 c_{i} 相同的节点当成一个连通分量(可以理解为一个大节点),并且每个连通分量内所有节点互相到达所用的时间都为 0,这样就能把题目中 c_{i} 相同的情况忽略掉。

然后再跑最短路,一共有 3 种算法供我们选择:

对比 3 种算法后,发现 Dijkstra 和 SPFA 都必须遍历完所有节点。而 BFS 找到目标节点后便可直接输出,综合起来 BFS 复杂度下限更低,所以用 BFS 解决。

AC Code:

#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
#include <climits>
#include <algorithm>
#include <cmath>
#include <set>
#include <map>
#include <bitset>
#include <cstdio>
#define ll long long
#define P pair<int, int>
#define MP make_pair
#define PU push_back
#define li(x) x << 1
#define ri(x) (x << 1) | 1
#define LLF LLONG_MAX >> 2
#define INF INT_MAX >> 1
using namespace std;
const int N = 5000 + 5;
int n, m, tot, head[N], d[N], c[N];
bitset<N> vis;      //可用bool数组代替,但时间和空间上都不占优

struct Edge{
    int u, v, w, nex;
}e[N << 1];

inline ll read(){
    ll f = 1, x = 0;
    char c = getchar();
    while(c < '0' || c > '9'){if(c == '-') f = -1; c = getchar();}
    while('0' <= c && c <= '9') x = (x << 3) + (x << 1) + (ll)(c - '0'), c = getchar();
    return x * f;
}

inline void write(ll x){
    if(x < 0) putchar('-'), x = -x;
    if(x > 9) write(x / 10);
    putchar(x % 10 + '0');
}

inline void add(int u, int v){
    e[++tot] = {u, v, 1, head[u]};
    head[u] = tot;
}

void BFS(int s, int t){
    vis = 0;      //bitset可以O(n/w)初始化(w为计算机的位数,一般w=32),bool数组只能O(n)
    queue<P> q;
    q.push({0, s});
    while(!q.empty()){
        int u = q.front().second;
        int stp = q.front().first;
        q.pop();
        if(u == t){      //找到了直接输出,BFS首解最优
            write(stp);
            putchar('\n');
            return;
        }
        if(vis[u]) continue;      //遍历过了就跳过,类似于Dijkstra
        vis[u] = true;     //没访问过就标记
        for(int i = head[u]; i; i = e[i].nex) q.push({stp + 1, e[i].v});        //将所有相邻节点入队
    }
}

int main(){
    n = read(), m = read();
    for(int i = 1; i <= n; ++i) c[i] = read();
    for(int i = 1, u, v; i < n; ++i){
        u = read(), v = read();
        add(c[u], c[v]), add(c[v], c[u]);      //一定不要忘了加上c[]!!!
    }
    while(m--){
        int s, t;
        s = read(), t = read();
        BFS(c[s], c[t]);      //同上
    }
    return 0;
}

完结撒花!!!