HDU 5867 Sparse Graph (2016年大连网络赛 I bfs+补图)

时间:2023-03-09 16:13:20
HDU 5867 Sparse Graph (2016年大连网络赛 I bfs+补图)

题意:给你n个点m条边形成一个无向图,问你求出给定点在此图的补图上到每个点距离的最小值,每条边距离为1

补图:完全图减去原图

完全图:每两个点都相连的图

其实就是一个有技巧的bfs,我们可以看到虽然点很多但边很少,就使用vector存下每个点在原图中可以到达其他的哪些点,再使用bfs寻找此时起点可以到的其他点(每个距离都是1,所以越早到距离越短),接着更新起点继续查找:我们需要使用数组记录此时起点不能到的一些点(就是vector中原图起点可以到的点),但每次通过起点判断其他所有的点会超时,因此我们就是用一个队列存储还没到过的点,每次就直接寻找这些点可否由此时起点到达就好

#include<set>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<string>
#include<cstdio>
#include<cstring>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define eps 1E-8
/*注意可能会有输出-0.000*/
#define Sgn(x) (x<-eps? -1 :x<eps? 0:1)//x为两个浮点数差的比较,注意返回整型
#define Cvs(x) (x > 0.0 ? x+eps : x-eps)//浮点数转化
#define zero(x) (((x)>0?(x):-(x))<eps)//判断是否等于0
#define mul(a,b) (a<<b)
#define dir(a,b) (a>>b)
typedef long long ll;
typedef unsigned long long ull;
const int Inf=<<;
const double Pi=acos(-1.0);
const int Mod=1e9+;
const int Max=;
vector<int> edge[Max];//可以连接的边
int vis[Max];//标记此时可否走
int ans[Max];
struct node
{
int npoi,step;
};
queue<node> bque;
queue<int> nque;//存下需要走到的点
void Init(int n)
{
while(!bque.empty())
bque.pop();
while(!nque.empty())
nque.pop();
for(int i=; i<=n; ++i)
{
ans[i]=-;
edge[i].clear();
vis[i]=;
}
return;
}
void Mark(int p,int f)//标记这些点可否走
{
int len=edge[p].size();
for(int i=; i<len; ++i)
vis[edge[p][i]]=f;
return;
}
void Bfs(int n,int s)//补图的bfs
{
int len=n-;
node tem,hh;
tem.step=,tem.npoi=s;
bque.push(tem);
vis[s]=;
while(!bque.empty())
{
tem=bque.front();
bque.pop();
Mark(tem.npoi,);//按照原图的边标记不能走
int tmp=len,tmp2;
while(tmp--)
{
tmp2=nque.front();//这些点都是没有走到的
nque.pop();
if(!vis[tmp2])
{
len--;
hh.step=tem.step+;
hh.npoi=tmp2;
bque.push(hh);
ans[tmp2]=hh.step;
}
else
nque.push(tmp2);
if(!len)
return;
}
Mark(tem.npoi,);
}
return;
}
int main()
{
int t,n,m;
int u,v,s;
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&n,&m);
Init(n);
for(int i=; i<m; ++i)
{
scanf("%d %d",&u,&v);
edge[u].push_back(v);
edge[v].push_back(u);
}
scanf("%d",&s);
for(int i=; i<=n; ++i)
if(i!=s)
nque.push(i);
Bfs(n,s);
int len=n-;
for(int i=; i<=n; ++i)
{
if(i!=s)
{
--len;
if(len)
printf("%d ",ans[i]);
else
printf("%d\n",ans[i]);
}
}
}
return ;
}