要求通过位运算操作将整数 x 转化为 y,先尝试一下求最小代价或判断:
#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操作只能将位从 变为 。OR操作只能将位从 变为 。
发现规律:若 y 的某位为 而 x 对应位为 ,必须通过 OR 操作;若 y 的某位为 而 x 对应位为 ,则必须通过 AND 操作。
然后就 AC 了:
#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 了 ,但是由于竖向排列图有点丑。

