#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;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
2 ms |
3152 KB |
Output is correct |
2 |
Correct |
2 ms |
3028 KB |
Output is correct |
3 |
Correct |
2 ms |
2988 KB |
Output is correct |
4 |
Correct |
2 ms |
3028 KB |
Output is correct |
5 |
Correct |
118 ms |
23844 KB |
Output is correct |
6 |
Correct |
123 ms |
23416 KB |
Output is correct |
7 |
Correct |
151 ms |
19580 KB |
Output is correct |
8 |
Correct |
117 ms |
20428 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
2 ms |
3028 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
2 ms |
3028 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
2 ms |
3152 KB |
Output is correct |
2 |
Correct |
2 ms |
3028 KB |
Output is correct |
3 |
Correct |
2 ms |
2988 KB |
Output is correct |
4 |
Correct |
2 ms |
3028 KB |
Output is correct |
5 |
Correct |
118 ms |
23844 KB |
Output is correct |
6 |
Correct |
123 ms |
23416 KB |
Output is correct |
7 |
Correct |
151 ms |
19580 KB |
Output is correct |
8 |
Correct |
117 ms |
20428 KB |
Output is correct |
9 |
Incorrect |
2 ms |
3028 KB |
Output isn't correct |
10 |
Halted |
0 ms |
0 KB |
- |