1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| #include <bits/stdc++.h> #define mp make_pair #define pb push_back #define sz(x) (int)x.size() #define all(x) begin(x), end(x) #define fi first #define se second #define debug(x) cerr << #x << " " << x << '\n' using namespace std; using ll = long long; using pii = pair<int,int>; using pli = pair<ll,int>; const int INF = 0x3f3f3f3f, N = 2e5 + 5; const ll LINF = 1e18 + 5; constexpr int mod = 1e9 + 7; int n, m, s, dis[N]; vector<int> G[N]; void init() { for(int i=1; i<=n; i++) G[i].clear(); } void bfs(int s) { for(int i=1; i<=n; i++) dis[i] = -1; dis[s] = 0; set <int> s1, s2; for(int i=1; i<=n; i++) if(i!=s) s1.insert(i); queue <int> q; q.push(s); while(sz(q)) { int u = q.front(); q.pop(); for(int v : G[u]) { auto it = s1.find(v); if(it!=s1.end()) { s2.insert(v); s1.erase(it); } } for(auto it : s1) dis[it] = dis[u] + 1, q.push(it); swap(s1, s2); s2.clear(); } } void solve() { scanf("%d%d", &n, &m); init(); for(int i=1; i<=m; i++) { int u, v; scanf("%d%d", &u, &v); G[u].pb(v); G[v].pb(u); } scanf("%d", &s); bfs(s); for(int i=1,j=0; i<=n; i++) if(i!=s) { j++; printf("%d%c", dis[i], " \n"[j==n-1]); } } int main() { int T; scanf("%d", &T); while(T--) solve(); return 0; }
|