hdu5876 Sparse Graph(补图最短路 bfs)
题目链接:hdu5876 Sparse Graph
详见代码。。
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<queue> 5 #include<vector> 6 #include<set> 7 using namespace std; 8 const int N = 200001; 9 const int inf = 0x3f3f3f3f; 10 int n, m; 11 vector<vector<int> >g; 12 int d[N]; 13 void bfs(int s){ 14 int u,v,i,j; 15 queue<int>q; 16 set<int>a; //不邻接的点 17 set<int>b; //未扩展的点 18 set<int>::iterator it; 19 for(i = 1; i <= n; ++i) 20 a.insert(i); 21 a.erase(s); 22 q.push(s); 23 while(!q.empty()){ 24 u=q.front(); 25 q.pop(); 26 for(j=0;j<g[u].size();++j){ 27 v=g[u][j]; 28 if(!a.count(v)) 29 continue; 30 b.insert(v); 31 a.erase(v); 32 } 33 for(it = a.begin(); it != a.end(); it++){ 34 d[*it] = d[u] + 1; 35 q.push(*it); 36 } 37 a.swap(b); 38 b.clear(); 39 } 40 } 41 int main(){ 42 int t, i, j, x, y, s, f; 43 scanf("%d", &t); 44 while(t--){ 45 scanf("%d %d", &n, &m); 46 memset(d, inf, sizeof(d)); 47 g.clear(); 48 g.resize(N+1); 49 for(i = 0; i < m; ++i){ 50 scanf("%d %d", &x, &y); 51 g[x].push_back(y); 52 g[y].push_back(x); 53 } 54 scanf("%d", &s); 55 d[s] = 0; 56 bfs(s); 57 f = 0; 58 for(i = 1; i <= n; ++i){ 59 if(i == s)continue; 60 if(d[i] == inf) 61 printf("-1\n"); 62 else if(!f){ 63 printf("%d", d[i]); 64 f = 1; 65 } 66 else 67 printf(" %d",d[i]); 68 } 69 printf("\n"); 70 } 71 return 0; 72 }