This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
const int nx=1e5+5;
int n, q, deg[nx], lvl[nx], u, v, t, res, rt, cnt[nx], lf;
vector<int> d[nx];
void dfs(int u, int p)
{
lvl[u]=lvl[p]+1;
if (d[u].size()==1) deg[u]++, lf++;
for (auto v:d[u]) if (v!=p) dfs(v, u), deg[u]+=deg[v];
if (deg[u]>2) deg[u]=((deg[u]%2)==1)?1:2;
if (u!=rt) res+=deg[u];
if (deg[u]==2&&u!=rt) cnt[u]=1;
}
void dfs2(int u, int p)
{
for (auto v:d[u]) if (v!=p) cnt[v]+=cnt[u], dfs2(v, u);
}
int main()
{
cin.tie(NULL)->sync_with_stdio(false);
cin>>n>>q;
for (int i=1; i<n; i++) cin>>u>>v, d[u].push_back(v), d[v].push_back(u);
for (int i=1; i<=n; i++) if (d[i].size()>1) rt=i;
dfs(rt, rt);
dfs2(rt, rt);
while (q--)
{
cin>>t>>u;
if ((lf+(d[u].size()!=1))%2==1) cout<<-1<<'\n';
else if (d[u].size()==1) cout<<res+1<<'\n';
else cout<<res+(lvl[u]-2*cnt[u])<<'\n';
}
}
/*
6 6
1 2
1 3
2 4
2 5
5 6
1 1
1 2
1 3
1 4
1 5
1 6
7
6
-1
-1
7
-1
8 8
5 4
5 6
4 2
4 3
4 1
6 7
7 8
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
*/
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |