题目描述
给定长度为 n 的数列 a,如果 ai&aj≠0a_i \& a_j\neq 0ai&aj=0(按位与),则在 i,j 之间存在一条长度为 ai+aja_i+a_jai+aj 的边,求 1 至所有点的最短路。
输入描述:
第一行一个正整数 n。 接下来一行 n 个整数 a1∼ana_1\sim a_na1∼an。
输出描述:
输出一行 n 个整数,第 i 个为 1 到 i 的最短路长度。不能到达输出 -1。
示例1
输入
5 1 5 6 7 8
输出
0 6 17 8 -1
对于 20%20\%20% 的数据, n≤10n\leq 10n≤10。 对于 40%40\%40% 的数据, n≤103n\leq 10^3n≤103。 对于另外 20%20\%20% 的数据, 所有的 aia_iai 均可表示为 2x+2y2^x+2^y2x+2y 的形式。 对于 100%100\%100% 的数据, 1≤n≤105,0≤ai≤2301\leq n\leq 10^5,0\leq a_i\leq 2^{30}1≤n≤105,0≤ai≤230。
题解:
如果最暴力地去思考的话,枚举个,但是
会T。那我们考虑每个数的二进制每一位为1的,给连一条额外的边,边权为
。这样如果两个数&为1的话就会通过这个二进制点连接,边权不变。此时跑个最短路即可。
注意额外的点可以开2e5以外,避免1e5+i会冲突。
/*keep on going and never give up*/
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ll long long
#define fast std::ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
inline int read()
{
int x=0,k=1; char c=getchar();
while(c<'0'||c>'9'){if(c=='-')k=-1;c=getchar();}
while(c>='0'&&c<='9')x=(x<<3)+(x<<1)+(c^48),c=getchar();
return x*k;
}
const int maxn=2e6+10;
const int mod=1e9+7;
int head[maxn],cnt,n,m,s,vis[maxn],dis[maxn];
struct QwQ{
int u,v,w,next;
}e[maxn];
struct node{
int w,now;
// inline bool operator <(const node &x)const{return w>x.w;}
};
bool operator<(const node &a,const node &b){
return a.w>b.w;
}
priority_queue<node>q;
void add(int u,int v,int w){
e[++cnt].v=v; e[cnt].w=w; e[cnt].next=head[u]; head[u]=cnt;}
void di(){
for(int i=1;i<=n+4e5+30;i++) dis[i]=1e16; dis[s]=0;
q.push((node){0,s});
while(!q.empty()) {
node x=q.top(); q.pop();
int u=x.now; if(vis[u]) continue;
vis[u]=1;
for(int i=head[u];i;i=e[i].next){
int v=e[i].v;
if(dis[v]>dis[u]+e[i].w) {
dis[v]=dis[u]+e[i].w;
q.push((node){dis[v],v});
}
}
}
}
signed main(){
n=read();
for(int i=1;i<=n;i++){
int x=read();
for(int j=0;j<=30;j++){
if(x&(1ll<<j)){
add(i,j+2e5,x);add(j+2e5,i,x);
}
}
} s=1; di();
for(int i=1;i<=n;i++){
if(dis[i]==1e16) cout<<-1<<" ";
else
cout<<dis[i]<<" ";
}
}