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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
| #include <cstdio> #include <vector> #include <algorithm> #define pb push_back using namespace std; template <class Type> void read (Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 1) + (x << 3) + c - '0'; flag && (x = ~x + 1); } template <class Type, class ...rest> void read (Type &x, rest &...y) { read(x), read(y...); } template <class Type> void write (Type x) { x < 0 && (putchar('-'), x = ~x + 1); x > 9 && (write(x / 10), 0); putchar('0' + x % 10); } const int N = 2e5 + 10; int top, stk[N]; vector <int> g[N], e[N]; int stmp, dfn[N], low[N]; int n, m, q, tot, s[N], p[N], d[N], w[N]; void tarjan (int u) { stk[++top] = u; low[u] = dfn[u] = ++stmp; for (int v : g[u]) if (!dfn[v]) { tarjan(v); low[u] = min(low[u], low[v]); if (low[v] == dfn[u]) { int x; ++tot; do { x = stk[top--]; e[tot].pb(x), e[x].pb(tot); } while (x ^ v); e[tot].pb(u), e[u].pb(tot); } } else low[u] = min(low[u], dfn[v]); } namespace LCA { int stmp, dfn[N], sz[N], son[N], top[N]; void dfs1 (int u = 1) { sz[u] = 1; son[u] = 0; for (int v : e[u]) if (v ^ p[u]) { p[v] = u; d[v] = d[u] + 1; s[v] = s[u] + w[v]; dfs1(v); sz[u] += sz[v]; if (sz[v] > sz[son[u]]) son[u] = v; } } void dfs2 (int u = 1, int t = 1) { top[u] = t; dfn[u] = ++stmp; if (!son[u]) return; dfs2(son[u], t); for (int v : e[u]) if (v ^ p[u] && v ^ son[u]) dfs2(v, v); } int lca (int a, int b) { while (top[a] ^ top[b]) { if (d[top[a]] < d[top[b]]) swap(a, b); a = p[top[a]]; } if (d[a] > d[b]) swap(a, b); return a; } void init () { stmp = 0; s[1] = w[1]; dfs1(), dfs2(); } } int calc (int a, int b) { int t = LCA::lca(a, b); return s[a] + s[b] - s[t] * 2; } int main () { int T; read(T); while (T--) { read(n, m); for (int a, b; m; --m) read(a, b), g[a].pb(b), g[b].pb(a); tot = n; tarjan(1), --top; for (int i = 1; i <= n; ++i) w[i] = 1; for (int i = n + 1; i <= tot; ++i) w[i] = 0; LCA::init(); read(q); for (int k; q; --q) { read(k); vector <int> h; h.resize(k); for (int i = 0; i < k; ++i) read(h[i]); sort(h.begin(), h.end(), [&](int a, int b) { return LCA::dfn[a] < LCA::dfn[b]; }); int res = calc(h.front(), h.back()); for (int i = 1; i < k; ++i) res += calc(h[i], h[i - 1]); res >>= 1; res += w[LCA::lca(h.front(), h.back())]; write(res - k), puts(""); } for (int i = 1; i <= n; ++i) g[i].clear(); for (int i = 1; i <= tot; ++i) e[i].clear(); stmp = 0; for (int i = 1; i <= n; ++i) dfn[i] = 0; } return 0; }
|