subtask1 挂了是个啥玩意
查看原帖
subtask1 挂了是个啥玩意
49093
_sys楼主2020/5/14 17:31

后面全过了,Subtask1 挂了。。。?

#include <bits/stdc++.h>
using namespace std;

const int Maxn = 400005;
int n, m, T, q, cnt, top, dfn_cnt, dfn_ct, tot, val[Maxn], node[Maxn], head[Maxn], dep[Maxn], dfn[Maxn], low[Maxn], sta[Maxn], anc[Maxn][21];
vector <int> Ve[Maxn];
struct edg
{
	int nxt, to;
} edge[2 * Maxn];
void add(int x, int y)
{
	edge[++cnt] = (edg){head[x], y};
	head[x] = cnt;
}
void tarjan(int u)
{
	dfn[u] = low[u] = ++dfn_cnt;
	sta[++top] = u;
	for (int i = head[u]; i; i = edge[i].nxt)
	{
		int to = edge[i].to;
		if (!dfn[to])
		{
			tarjan(to);
			if (low[to] >= dfn[u])
			{
				tot++;
				int x;
				do
				{
					x = sta[top--];
					Ve[x].push_back(tot), Ve[tot].push_back(x);
				}
				while (x != to);
				Ve[u].push_back(tot), Ve[tot].push_back(u);
			}
			low[u] = min(low[u], low[to]);
		}
		else low[u] = min(low[u], dfn[to]);
	}
}
void dfs(int u, int fa)
{
	anc[u][0] = fa;
	dep[u] = dep[fa] + 1;
	val[u] = val[fa] + (u <= n);
	dfn[u] = ++dfn_ct;
	for (vector <int> :: iterator it = Ve[u].begin(); it != Ve[u].end(); it++)
	{
		int to = *it;
		if (to != fa)
			dfs(to, u);
	}
}
void init(void)
{
	for (int j = 1; (1 << j) <= n; j++)
		for (int i = 1; i <= n; i++)
			anc[i][j] = anc[anc[i][j - 1]][j - 1];
}
int lca(int x, int y)
{
	if (dep[x] < dep[y]) swap(x, y);
	for (int i = 20; i >= 0; i--)
		if ((dep[x] - dep[y]) & (1 << i)) x = anc[x][i];
	if (x == y) return x;
	for (int i = 20; i >= 0; i--)
		if (anc[x][i] != anc[y][i]) x = anc[x][i], y = anc[y][i];
	return anc[x][0];
}
int main()
{
	scanf("%d", &T);
	while (T--)
	{
		for (int i = 1; i <= tot; i++)
			Ve[i].clear();
		memset(dfn, 0, sizeof(int[tot + 1]));
		tot = dfn_cnt = dfn_ct = top = cnt = 0;
		memset(low, 0, sizeof(int[n + 1]));
		memset(head, 0, sizeof(int[n + 1]));
		scanf("%d%d", &n, &m);
		for (int i = 1; i <= m; i++)
		{
			int x, y;
			scanf("%d%d", &x, &y);
			add(x, y), add(y, x);
		}
		tot = n;
		tarjan(1);
		dfs(1, 0);
		init();
		scanf("%d", &q);
		while (q--)
		{
			int ans = 0;
			int c;
			scanf("%d", &c);
			for (int i = 1; i <= c; i++)
				scanf("%d", &node[i]);
			sort(node + 1, node + 1 + c, [](int x, int y){return dfn[x] < dfn[y];});
			for (int i = 1; i < c; i++)
				ans += val[node[i]] + val[node[i + 1]] - 2 * val[lca(node[i], node[i + 1])];
			ans += val[node[1]] + val[node[c]] - 2 * val[lca(node[1], node[c])];
			printf("%d\n", ans / 2 - c + (lca(node[1], node[c]) <= n));
		}
	}
	return 0;
}
2020/5/14 17:31
加载中...