本文搬运自本人初中博客园博客,若图片加载不出来,可到原文查看:https://www.cnblogs.com/zhangtingxi/p/15673449.html

题目链接

题目

给定长度为 n 的数列 a,如果 (按位与),则在 i,j 之间存在一条长度为 的边,求 1 至所有点的最短路。

思路

暴力连边,边太多,最多 n2n^2 条,MLE+TLE。

于是考虑减少边的数量。

首先建32个虚点。

然后加入 aia_i 在第 kk 位上为1,就在 ii 和第 kk 个虚点当中连边,边权为 aia_i

这样最多有 n×32n\times 32 条边。

然后我们验证一下,假如 ai&aj0a_i\& a_j\neq 0,他们必有其中一位为都为1,经过两条边边权分别为 aia_iaja_j

符合题意。

然后代码就很简单了。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Problem: 最短路
// Contest: NowCoder
// URL: https://ac.nowcoder.com/acm/contest/11233/D
// Memory Limit: 524288 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;
ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+
(x<<3)+(ch^48);ch=getchar();}return x*f;}
//#define mo
#define N 200010
struct node
{
int x, y, z, n;
}d[N*32];
int n, m, i, j, k;
int ans[N], h[N], c[N], a[N];
int u, v, g;
queue<int>q;

void cun(int x, int y, int z)
{
// printf("%lld %lld %lld\n", x, y, z);
d[++k].x=x; d[k].y=y; d[k].z=z;
d[k].n=h[x]; h[x]=k;
}

signed main()
{
// freopen("tiaoshi.in","r",stdin);
// freopen("tiaoshi.out","w",stdout);
n=read();
for(i=1; i<=n; ++i)
{
a[i]=read();
for(int k=0; k<=32; ++k)
if(a[i]&(1<<k))
cun(i, n+k+1, a[i]), cun(n+k+1, i, a[i]);
}
memset(ans, 0x3f, sizeof(ans));
ans[1]=0; q.push(1);
while(!q.empty())
{
u=q.front(); q.pop();
c[u]=0;
for(g=h[u]; g; g=d[g].n)
{
v=d[g].y;
if(ans[u]+d[g].z<ans[v])
{
ans[v]=ans[u]+d[g].z;
if(!c[v]) c[v]=1, q.push(v);
}
}
}
for(i=1; i<=n; ++i)
printf("%lld ", (ans[i]==ans[0] ? -1 : ans[i]));
return 0;
}