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;
int n, dp[100002][2][2], p[100002], node1, node2;
vector<int>G[100002];
int preset[100002];
int find (int x) {
if (p[x] == x)
return x;
return p[x] = find(p[x]);
}
void dfs (int nod, int par) {
vector<int>sons;
for (auto it : G[nod])
if (it != par) {
sons.push_back(it);
dfs(it, nod);
}
for (int cul = 0; cul < 2; cul++)
for (int cul2 = 0; cul2 < 2; cul2++) {
if (cul2 && nod == 1)
continue;
if (preset[nod] != -1 && preset[nod] != cul)
continue;
int blue = (cul2 + (preset[nod] != -1 && preset[node1 + node2 - nod] == 1));
if (blue == 2 && par == node1 + node2 - nod)
blue--;
if (blue == 2)
continue;
dp[nod][cul][cul2] = 0;
for (auto it : sons)
dp[nod][cul][cul2] += dp[it][0][cul];
if (!blue) {
int add = -1e9;
for (auto it : sons)
add = max(add, dp[it][1][cul] - dp[it][0][cul]);
dp[nod][cul][cul2] += add;
}
dp[nod][cul][cul2] += (!cul);
}
}
void reset() {
for (int k = 1; k <= n; k++)
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
dp[k][i][j] = -1e9;
}
int main ()
{
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++)
p[i] = i;
for (int i = 1; i <= n; i++) {
int x, y;
cin >> x >> y;
if (find(x) == find(y))
node1 = x, node2 = y;
else {
G[x].push_back(y);
G[y].push_back(x);
}
p[find(x)] = find(y);
}
memset(preset, -1, sizeof(preset));
int ans = 1e9;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++) {
reset();
preset[node1] = i;
preset[node2] = j;
dfs(1, 0);
ans = min(ans, n - max(dp[1][0][0], dp[1][1][0]));
}
cout << (ans >= n ? -1 : 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... |