跳到正文

题解

P13712 淘汰(Easy ver.)题解

Forever_Rain约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月12日
篇幅
约 4 分钟
题目
P13712

版本

  1. v1当前

要求通过位运算操作将整数 x 转化为 y,先尝试一下求最小代价或判断:

C++
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
int main(){
    ios::sync_with_stdio(0);cin.tie(0);
    int T;cin>>T;
    while(T--){
        ll x,y,a,b,c,d;
        cin>>x>>y>>a>>b>>c>>d;
        ll cost=0,cu=x;
        while(cu!=y){
            ll andv=cu&a;
            ll orv=cu|b;
            if(abs(andv-y)<abs(orv-y)){
                if(andv==cu) break;
                cu=andv;
                cost+=c;
            }else{
                if(orv==cu) break;
                cu=orv;
                cost+=d;
            }
            if(cost>1e6) break;
        }
        cout<<(cu==y?cost:-1)<<'\n';
    }
    return 0;
}

不测样例自信交了一发。

然后喜提WA。

……

我们充分发扬人类智慧,所想到了需要用搜索。

所以使用我们使用 BFS 保证首次到达 y 时的代价最小,记录使用哈希表即可。

我们发现:

  • AND 操作只能将位从 11 变为 00。
  • OR 操作只能将位从 00 变为 11。

发现规律:若 y 的某位为 11 而 x 对应位为 00,必须通过 OR 操作;若 y 的某位为 00 而 x 对应位为 11,则必须通过 AND 操作。

然后就 AC 了:

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

int main(){
    ios::sync_with_stdio(0);cin.tie(0);
    int T;cin>>T;
    while(T--){
        ll x,y,a,b,c,d;cin>>x>>y>>a>>b>>c>>d;

        unordered_map<ll,ll> vis;  // 记录访问状态和代价
        queue<ll> q;
        q.push(x);
        vis[x]=0;

        ll ans=-1;
        while(!q.empty()){
            ll u=q.front();q.pop();

            if(u==y){
                ans=vis[u];
                break;
            }

            // 尝试AND操作
            ll v1=u&a;
            if(!vis.count(v1)){
                vis[v1]=vis[u]+c;
                q.push(v1);
            }

            // 尝试OR操作
            ll v2=u|b;
            if(!vis.count(v2)){
                vis[v2]=vis[u]+d;
                q.push(v2);
            }
        }
        cout<<ans<<'\n';
    }
    return 0;
}

AC 了 ,但是由于竖向排列图有点丑。

原文