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>
#define ll long long
#define ld long double
#define sp ' '
#define en '\n'
#define smin(a, b) a = min(a, b)
#define smax(a, b) a = max(a, b)
using namespace std;
const int N = 1e5 + 2;
const int inf = 2e9;
struct Dsu {
int p[N];
void Init(int n) {
for (int i = 1; i <= n; i++) p[i] = i;
}
int Find(int x) {
if (x == p[x]) return x;
return p[x] = Find(p[x]);
}
void Unite(int u, int v) {
u = Find(u); v = Find(v);
p[v] = u;
}
}dsu;
vector<int> g[N];
int sta[N], col[N];
int dp[N][2][2];
int Resi(int s, int e) {
if (sta[s] == 0) {
dp[s][col[s]][0] = col[s];
int mx = 0;
for (int u : g[s]) {
if (u == e) continue;
Resi(u, s);
smax(mx, dp[u][0][col[s]]);
dp[s][col[s]][0] += dp[u][0][col[s]];
}
if (mx == inf) dp[s][col[s]][0] = mx;
return dp[s][col[s]][0];
}
for (int u : g[s]) if (u != e) Resi(u, s);
for (int j = 0; j < 2; j++) {
if (col[s] < 2 && col[s] != j) continue;
dp[s][j][0] = dp[s][j][1] = j;
int sum = 0;
int mx = 0;
int cnt = 0;
for (int u : g[s]) {
if (u == e) continue;
if (dp[u][0][j] == inf) {mx = u; cnt += 1;}
if (mx != u) sum += dp[u][0][j];
if (mx != u)dp[s][j][0] += dp[u][0][j];
if (mx != u)dp[s][j][1] += dp[u][0][j];
}
if (cnt >= 2) {
dp[s][j][0] = dp[s][j][1] = inf;
continue;
}
if (cnt == 1) {
dp[s][j][1] = inf;
if (dp[mx][1][j] != inf) dp[s][j][0] += dp[mx][1][j];
else dp[s][j][0] = inf;
continue;
}
mx = -inf;
for (int u : g[s]) {
if (u == e) continue;
if (dp[u][1][j] != inf) smax(mx, dp[u][0][j] - dp[u][1][j]);
}
if (mx == -inf) dp[s][j][0] = inf;
else dp[s][j][0] -= mx;
}
return min({dp[s][0][0], dp[s][1][0]});
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n; cin >> n;
dsu.Init(n);
int A, B; A = B = 0;
for (int i = 0; i < n; i++) {
int u, v;
cin >> u >> v;
if (dsu.Find(u) != dsu.Find(v)) {
dsu.Unite(u, v);
g[u].push_back(v);
g[v].push_back(u);
}
else {
A = u;
B = v;
}
}
for (int i = 1; i <= n; i++) {
sta[i] = 1; col[i] = 2;
}
for (int i = 1; i <= n; i++) for (int j = 0; j < 4; j++) dp[i][j / 2][j % 2] = inf;
col[A] = col[B] = 0;
int ans = Resi(1, 0);
for (int i = 1; i <= n; i++) for (int j = 0; j < 4; j++) dp[i][j / 2][j % 2] = inf;
col[B] = 1; sta[A] = 0;
smin(ans, Resi(1, 0));
for (int i = 1; i <= n; i++) for (int j = 0; j < 4; j++) dp[i][j / 2][j % 2] = inf;
col[A] = 1; sta[B] = 0;
smin(ans, Resi(1, 0));
for (int i = 1; i <= n; i++) for (int j = 0; j < 4; j++) dp[i][j / 2][j % 2] = inf;
col[B] = 0; sta[A] = 1;
smin(ans, Resi(1, 0));
if (ans == inf) ans = -1;
cout << ans << en;
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... |