#include <algorithm>
#include <iostream>
#include <numeric>
#include <cassert>
#include <vector>
#include <queue>
#include <stack>
typedef long long llong;
const int MAXN = 200000 + 10;
const int MOD = 1e9 + 7;
const int INF = 2e9;
int n, q;
int sz[MAXN];
llong sumDist[MAXN];
std::vector <int> g[MAXN];
void dfsSize(int node, int par)
{
sz[node] = (g[node].size() == 1);
sumDist[node] = 0;
for (const int &u : g[node])
{
if (u == par)
{
continue;
}
dfsSize(u, node);
sz[node] += sz[u];
sumDist[node] += sumDist[u] + sz[u];
}
}
llong findCentroid(int node, int par, llong sum)
{
for (const int &u : g[node])
{
if (u == par)
{
continue;
}
if (sz[u] > sz[1] / 2)
{
return findCentroid(u, node, sum + ((sz[1] - sz[u]) - sz[u]));
}
}
return sum;
}
llong calc()
{
dfsSize(1, 0);
if (sz[1] & 1) return -1;
return findCentroid(1, 0, sumDist[1]);
}
int a[MAXN];
void solve()
{
for (int i = 1 ; i <= q ; ++i)
{
int d;
int cnt = n;
std::cin >> d;
for (int j = 1 ; j <= d ; ++j)
{
std::cin >> a[j];
g[a[j]].push_back(++cnt);
g[cnt].push_back(a[j]);
}
std::cout << calc() << '\n';
for (int j = 1 ; j <= d ; ++j)
{
g[a[j]].pop_back();
g[cnt--].pop_back();
}
}
}
void input()
{
std::cin >> n >> q;
for (int i = 2 ; i <= n ; ++i)
{
int u, v;
std::cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
}
void fastIOI()
{
std::ios_base :: sync_with_stdio(0);
std::cout.tie(nullptr);
std::cin.tie(nullptr);
}
int main()
{
fastIOI();
input();
solve();
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
6492 KB |
Output is correct |
2 |
Execution timed out |
1088 ms |
8260 KB |
Time limit exceeded |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
13 ms |
10572 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
13 ms |
11348 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
202 ms |
8784 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
1043 ms |
9916 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
1052 ms |
11612 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
6492 KB |
Output is correct |
2 |
Execution timed out |
1088 ms |
8260 KB |
Time limit exceeded |
3 |
Halted |
0 ms |
0 KB |
- |