|
| 1 | +#include <bits/stdc++.h> |
| 2 | + |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +int const N = 1e5 + 1; |
| 6 | +int t, n, m, idx[N], low[N], dfs, cost[2][N]; |
| 7 | +bool vis[N]; |
| 8 | +vector<vector<int> > g; |
| 9 | +vector<pair<int, int> > edges; |
| 10 | +set<int> ap; |
| 11 | +queue<int> q; |
| 12 | + |
| 13 | +void DFS(int v, int par) { |
| 14 | + idx[v] = low[v] = dfs++; |
| 15 | + |
| 16 | + int ch = 0; |
| 17 | + for(int i = 0, u; i < g[v].size(); ++i) { |
| 18 | + u = g[v][i]; |
| 19 | + if(idx[u] == -1) { |
| 20 | + ++ch; |
| 21 | + |
| 22 | + DFS(u, v); |
| 23 | + low[v] = min(low[v], low[u]); |
| 24 | + |
| 25 | + if(par == -1 && ch > 1) |
| 26 | + ap.insert(v); |
| 27 | + else if(par != -1 && low[u] >= idx[v]) |
| 28 | + ap.insert(v); |
| 29 | + } else if(par != u) |
| 30 | + low[v] = min(low[v], idx[u]); |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +int BFS(int src, int idx) { |
| 35 | + memset(cost[idx], 0, sizeof cost[idx]); |
| 36 | + memset(vis, false, sizeof vis); |
| 37 | + while(!q.empty()) q.pop(); |
| 38 | + |
| 39 | + q.push(src); |
| 40 | + |
| 41 | + while(!q.empty()) { |
| 42 | + int fr = q.front(); |
| 43 | + q.pop(); |
| 44 | + |
| 45 | + if(vis[fr]) |
| 46 | + continue; |
| 47 | + vis[fr] = true; |
| 48 | + |
| 49 | + for(int i = 0; i < g[fr].size(); ++i) { |
| 50 | + cost[idx][g[fr][i]] = cost[idx][fr] + 1; |
| 51 | + q.push(g[fr][i]); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return 0; |
| 56 | +} |
| 57 | + |
| 58 | +int main() { |
| 59 | + scanf("%d", &t); |
| 60 | + while(t-- != 0) { |
| 61 | + scanf("%d %d", &n, &m); |
| 62 | + |
| 63 | + g.clear(); |
| 64 | + g.resize(n); |
| 65 | + edges.clear(); |
| 66 | + edges.resize(m); |
| 67 | + for(int i = 0, a, b; i < m; ++i) { |
| 68 | + scanf("%d %d", &a, &b); |
| 69 | + --a, --b; |
| 70 | + g[a].push_back(b); |
| 71 | + g[b].push_back(a); |
| 72 | + edges[i] = {a, b}; |
| 73 | + } |
| 74 | + |
| 75 | + memset(idx, -1, sizeof idx); |
| 76 | + ap.clear(); |
| 77 | + dfs = 0; |
| 78 | + DFS(0, -1); |
| 79 | + |
| 80 | + if(ap.empty()) { |
| 81 | + printf("%d\n", n); |
| 82 | + } else { |
| 83 | + BFS(0, 0); |
| 84 | + BFS(n - 1, 1); |
| 85 | + |
| 86 | + int v1 = 1e9, v2 = -1e9, i, v; |
| 87 | + for(set<int>::iterator it = ap.begin(); it != ap.end(); ++it) { |
| 88 | + v = *it; |
| 89 | + |
| 90 | + if(cost[0][v] < v1 && cost[1][v] > v2) { |
| 91 | + i = v; |
| 92 | + v1 = cost[0][v]; |
| 93 | + v2 = cost[1][v]; |
| 94 | + } |
| 95 | + } |
| 96 | + printf("%d\n", i + 1); |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + return 0; |
| 101 | +} |
0 commit comments