【牛客IOI周赛26-普及组 D-最短路 】题解

题目链接

题目

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

思路

暴力连边,边太多,最多 \(n^2\) 条,MLE+TLE。

于是考虑减少边的数量。

首先建32个虚点。

然后加入 \(a_i\) 在第 \(k\) 位上为1,就在 \(i\) 和第 \(k\) 个虚点当中连边,边权为 \(a_i\)

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

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

符合题意。

然后代码就很简单了。

Code

// 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;
}


posted @ 2021-12-10 18:59  zhangtingxi  阅读(208)  评论(0编辑  收藏  举报