#23137. Graph Built by XOR
Maggie114514 · · 个人记录
题目
#23137. Graph Built by XOR
然后呢。这大概是今天模拟赛的第二题。
由于第一题太简单,第三题太复杂没听懂,第四题是个猎奇大构造,场上滚木个人能想出来。所以还是来写这个比较像人的题目的题解吧。(说了一段废话试图让自己的题解显得很有内容)
思路
其实这个题也不是很人性化。但相对来说思路还是比较自然的。
首先,这个东西如果暴力建图是
显然。这个东西肯定和位运算有关。所以很自然就能想到 那你就只能和我一起受着了。
其实
我解释的不是特别清楚,所以如果你还是不会的话建议去自学一下喵。
好了,让我们真正开始做这个题。
-
建
Trie 树: 将所有节点a_i 插入到一颗01-Trie 树中,由于a_i 的值可能重复,所以我们要在叶子结点处维护一下所有a_i 值相等的i 节点。 -
在
Trie 上查询与提取: 在Dijkstra 算法中,每次从优先队列取出一个当前距离最小的节点u 后,我们需要找到所有满足a_u⊕a_v≤m 的所有的v 并进行更新。查找我们分为以下两种情况:-
设
x 为a_u 第k 位上的数字,b 为m 第k 位上的数字。 -
若
b=0 : 则只能查找ch[x] 这颗子树内的节点(因为其他的一定不满足) -
若
b=1 :- 若查找
ch[x] 这颗子树内的节点,这整颗子树都能被提取,因为这一位一定是0 严格小于b ,提取完以后记得删除子树,避免重复提取。 - 若查找
ch[x^1] 这颗子树内的节点,我们就继续往下查找,重复整个过程就行。
- 若查找
-
-
Dijkstra 状态更新: 当我们查找到v 节点时,更新dis[v]=dis[u]+a[u]+a[v] ,注意要进入优先队列的是dis[v]+a[v] 因为a[v] 大小也会对路径有所影响。(特别坑我一开始就错的这个地方!!)
好啦,整个题目的思路就是这样~
代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=2e5+10;
const int M=N*31;
const ll inf=1e15;
struct tt{
int ch[2],h;
}t[M];
struct hh{
int v1;
ll w1;
bool operator < (const hh &x)const{
return w1>x.w1;
}
};
int T,n,m,a[N],vis[N],nxt[N],tot;
ll dis[N];
priority_queue<hh>q;
void init(){
tot=1;
t[1].ch[0]=t[1].ch[1]=0;
t[1].h=0;
}
void insert(int x,int id){
int p=1;
for(int i=29;i>=0;i--){
int b=(x>>i)&1;
if(!t[p].ch[b]){
t[p].ch[b]=++tot;
t[tot].ch[0]=t[tot].ch[1]=0;
t[tot].h=0;
}
p=t[p].ch[b];
}
nxt[id]=t[p].h;
t[p].h=id;
}
void dfs(int p,int u,ll du){
if(!p)return;
for(int v=t[p].h;v;v=nxt[v]){
ll nd=du+a[u]+a[v];
if(nd<dis[v]){
dis[v]=nd;
q.push({v,nd+a[v]});
}
}
t[p].h=0;
dfs(t[p].ch[0],u,du);
dfs(t[p].ch[1],u,du);
t[p].ch[0]=t[p].ch[1]=0;
}
void query(int p,int d,int u,ll du){
if(!p)return ;
if(d<0){
dfs(p,u,du);
return ;
}
int x=(a[u]>>d)&1;
int b=(m>>d)&1;
if(b==0){
query(t[p].ch[x],d-1,u,du);
}else{
dfs(t[p].ch[x],u,du);
t[p].ch[x]=0;
query(t[p].ch[x^1],d-1,u,du);
}
}
void diji(){
while(!q.empty())q.pop();
dis[1]=0;
q.push({1,(ll)a[1]});
while(!q.empty()){
hh now=q.top();
q.pop();
int u=now.v1;
if(vis[u])continue;
vis[u]=1;
if(u==n)break;
query(1,29,u,dis[u]);
}
}
signed main(){
// freopen("forget.in","r",stdin);
// freopen("forget.out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0);
cin>>T;
while(T--){
cin>>n>>m;
tot=0;
for(int i=1;i<=n;i++){
cin>>a[i];
dis[i]=inf;
vis[i]=0;
}
if(n==1){
cout<<0<<"\n";
continue;
}
if(m==0){
if(a[1]!=a[n])cout<<-1<<"\n";
else cout<<(ll)2*a[1]<<"\n";
continue;
}
if(a[1]==a[n]){
cout<<(ll)2*a[1]<<"\n";
continue;
}
init();
for(int i=1;i<=n;i++)insert(a[i],i);
diji();
if(dis[n]==inf)cout<<-1<<"\n";
else cout<<dis[n]<<"\n";
}
return 0;
}
后话
呃呃呃。其实这场拼暴力也有不少分。但是我太勤奋了所以也没有全部打完。对的。
最后 100+40+5+10=155 rk7
感谢观看~