标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 1520 Accepted Submission(s): 537
#include <cstdio> #include <cstring> #include <vector> #include <set> #include <queue> using namespace std; const int INF = 0x3f3f3f3f; const int MAXN = 2e5+5; vector<int> e[MAXN]; int dis[MAXN]; int n, m, s; void bfs() { set<int> s1, s2; set<int>::iterator it; for(int i = 1; i <= n; ++i){ if(i != s) s1.insert(i); } queue<int> q; q.push(s); dis[s] = 0; while(!q.empty()){ int u = q.front(); q.pop(); int len = e[u].size(); for(int i = 0; i < len; ++i){ int v = e[u][i]; if(s1.find(v) == s1.end()) continue; s1.erase(v); s2.insert(v); } for(it = s1.begin(); it != s1.end(); ++it){ q.push(*it); dis[*it] = dis[u]+1; } s1.swap(s2); s2.clear(); } } void solve() { memset(dis, INF, sizeof(dis)); for(int i = 1; i <= n; ++i) e[i].clear(); int u, v; while(m--){ scanf("%d%d", &u, &v); e[u].push_back(v); e[v].push_back(u); } scanf("%d", &s); bfs(); for(int i = 1; i <= n; ++i){ if(i == s) continue; if(dis[i] >= INF) dis[i] = -1; printf("%d", dis[i]); if(i != n) printf(" "); } printf("\n"); } int main() { int t; scanf("%d", &t); while(t--){ scanf("%d%d", &n, &m); solve(); } return 0; }
标签:
原文地址:http://www.cnblogs.com/inmoonlight/p/5873347.html