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;
#define ll long long
#define ar array
const int mxN=3e5, M=1e9+7;
int n, m, d[mxN], anc[mxN][19], dp[mxN], p[mxN], col[mxN];
vector<int> adj[mxN], adj2[mxN];
vector<ar<int, 2>> bad;
void dfs1(int u=0) {
for (int i=1; i<19; ++i)
anc[u][i]=anc[anc[u][i-1]][i-1];
for (int v : adj[u]) {
adj[v].erase(find(adj[v].begin(), adj[v].end(), u));
d[v]=d[u]+1, anc[v][0]=u;
dfs1(v);
}
}
int lca(int u, int v) {
if (d[u]>d[v])
swap(u, v);
for (int i=18; ~i; --i)
if (d[u]<=d[v]-(1<<i))
v=anc[v][i];
if (u==v)
return u;
for (int i=18; ~i; --i)
if (anc[u][i]^anc[v][i])
u=anc[u][i], v=anc[v][i];
return anc[u][0];
}
int lift(int u, int k) {
int r=u;
for (int i=0; i<19; ++i)
if (k&(1<<i))
r=anc[r][i];
return r;
}
void dfs2(int u=0) {
for (int v : adj[u])
dfs2(v), dp[u]+=dp[v];
}
int find(int i) {
return i^p[i]?p[i]=find(p[i]):i;
}
void merge(int u, int v) {
u=find(u), v=find(v);
if (u==v)
return;
p[v]=u;
}
void dfs3(int u, int c) {
col[u]=c;
for (int v : adj2[u]) {
if (col[v]==-1)
dfs3(v, c^1);
else if (col[u]==col[v]) {
cout << 0;
exit(0);
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i=1; i<n; ++i) {
int u, v;
cin >> u >> v, --u, --v;
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs1();
for (int i=0; i<m; ++i) {
int u, v;
cin >> u >> v, --u, --v;
int uv=lca(u, v), lu=-1, lv=-1;
if (u^uv) {
lu=lift(u, d[u]-d[uv]-1);
++dp[u], --dp[lu];
}
if (v^uv) {
lv=lift(v, d[v]-d[uv]-1);
++dp[v], --dp[lv];
}
if (u^uv&&v^uv)
bad.push_back({lu, lv});
}
dfs2();
iota(p, p+n, 0);
for (int i=1; i<n; ++i)
if (dp[i])
merge(i, anc[i][0]);
for (ar<int, 2>& a : bad) {
if (dp[a[0]]&&dp[a[1]]) {
cout << 0;
return 0;
}
int u=find(a[0]), v=find(a[1]);
adj2[u].push_back(v);
adj2[v].push_back(u);
}
memset(col, -1, sizeof(col));
int ans=1;
for (int i=1; i<n; ++i) {
if (i^p[i]||col[i]^-1)
continue;
dfs3(i, 0);
ans=2*ans%M;
}
cout << ans;
return 0;
}
# | 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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |