跳到正文

题解

e

zykaris约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v1当前

淘汰(Easy ver.)题解

题意

这里不再叙述

思路

很明显此题为位运算,我们要搭配其他算法来解决,赛时写贪心和动态规划被卡爆了,万不得已才开始建图跑最短路

主要难点是将图拆解成步骤,可以通过计算最大位数来以图论思想做出此题。

所以建议添加图论标签(bushi)

C++
#include <bits/stdc++.h>
using namespace std;

using ll = long long;

const ll INF = 1e18;

ll dijkstra(int x, int y, int a, int b, int c, int d, int k) {
    int maxn = 1 << k;
    vector<ll> D(maxn, INF);
    priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<>> Q;
    Q.emplace(0, x);
    D[x] = 0;
    while (!Q.empty()) {
        auto [cost, u] = Q.top(); Q.pop();
        if (u == y) return cost;
        if (cost > D[u]) continue;
        int v1 = u & a;
        if (D[v1] > cost + c) {
            D[v1] = cost + c;
            Q.emplace(D[v1], v1);
        }
        int v2 = u | b;
        if (D[v2] > cost + d) {
            D[v2] = cost + d;
            Q.emplace(D[v2], v2);
        }
    }
    return D[y] == INF ? -1 : D[y];
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int T; cin >> T;
    while (T--) {
        int x, y, a, b, c, d; cin >> x >> y >> a >> b >> c >> d;
        int k = 0;
        // 确定最大位数 k
        for (int val : {x, y, a, b}) {
            k = max(k, val ? 32 - __builtin_clz(val) : 0);
        }
        k = max(k, 1);
        cout << dijkstra(x, y, a, b, c, d, k) << '\n';
    }
    return 0;
}
原文