您的位置:首页 > 其它

HDU 5876 Sparase Graph(补图上的bfs)

2016-09-11 08:55 267 查看
//
//  main.cpp
//  Richard
//
//  Created by 邵金杰 on 16/9/11.
//  Copyright © 2016年 邵金杰. All rights reserved.
//

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<set>
using namespace std;
const int maxv=200000+10;
const int maxn=40000+10;
const int inf=99999999;
struct edge{
int u,v,next;
}edge[maxn*2];
int head[maxv],dist[maxv];
int n,e;
int cnt;
int s;
void add_edge(int u,int v)
{
edge[cnt].u=u;
edge[cnt].v=v;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void complement_graph_bfs()
{
set<int> ta,tb;
set<int>::iterator it;
for(int i=1;i<=n;i++) dist[i]=inf;
for(int i=1;i<=n;i++) if(i!=s) ta.insert(i);
dist[s]=0;
queue<int> q;
q.push(s);
while(!q.empty())
{
int now=q.front();q.pop();
for(int i=head[now];i!=-1;i=edge[i].next){
if(ta.find(edge[i].v)!=ta.end()){
ta.erase(edge[i].v);
tb.insert(edge[i].v);
}
}
for(it=ta.begin();it!=ta.end();it++) {dist[*it]=dist[now]+1;q.push(*it);}
ta.swap(tb);tb.clear();
}
for(int i=1;i<=n;i++) if(i!=s) {printf("%d%s",dist[i]==inf?-1:dist[i],i<n?" ":"");}
printf("\n");
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
cnt=0;
memset(head,-1,sizeof(head));
scanf("%d%d",&n,&e);
int u,v;
for(int i=0;i<e;i++){
scanf("%d%d",&u,&v);
add_edge(u,v);
add_edge(v,u);
}
scanf("%d",&s);
complement_graph_bfs();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: