题目链接:hdu5876 Sparse Graph
详见代码。。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
#include<set>
using namespace std;
const int N = ;
const int inf = 0x3f3f3f3f;
int n, m;
vector<vector<int> >g;
int d[N];
void bfs(int s){
int u,v,i,j;
queue<int>q;
set<int>a; //不邻接的点
set<int>b; //未扩展的点
set<int>::iterator it;
for(i = ; i <= n; ++i)
a.insert(i);
a.erase(s);
q.push(s);
while(!q.empty()){
u=q.front();
q.pop();
for(j=;j<g[u].size();++j){
v=g[u][j];
if(!a.count(v))
continue;
b.insert(v);
a.erase(v);
}
for(it = a.begin(); it != a.end(); it++){
d[*it] = d[u] + ;
q.push(*it);
}
a.swap(b);
b.clear();
}
}
int main(){
int t, i, j, x, y, s, f;
scanf("%d", &t);
while(t--){
scanf("%d %d", &n, &m);
memset(d, inf, sizeof(d));
g.clear();
g.resize(N+);
for(i = ; i < m; ++i){
scanf("%d %d", &x, &y);
g[x].push_back(y);
g[y].push_back(x);
}
scanf("%d", &s);
d[s] = ;
bfs(s);
f = ;
for(i = ; i <= n; ++i){
if(i == s)continue;
if(d[i] == inf)
printf("-1\n");
else if(!f){
printf("%d", d[i]);
f = ;
}
else
printf(" %d",d[i]);
}
printf("\n");
}
return ;
}