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;
#pragma GCC optimize ("Ofast")
#define F first
#define S second
#define vi vector<int>
#define vvi vector<vi>
#define pi pair<int, int>
#define vpi vector<pi>
#define vb vector<bool>
#define vvb vector<vb>
#define pb push_back
#define ppb pop_back
#define read(a) for(auto &x:a) cin >> x;
#define print(a) for(auto x:a) cout << x << " "; cout << "\n";
#define vc vector<char>
#define vvc vector<vc>
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define int long long
#define ld long double
const int INF = 1e18;
const int inf = 1e9;
struct DSU{
vi link, sz;
DSU(int n){
link = sz = vi(n+1);
for(int i=1; i<=n; i++)
link[i] = i, sz[i] = 1;
}
int find(int x){
if(x == link[x]) return x;
return link[x] = find(link[x]);
}
bool same(int a, int b){
return find(a) == find(b);
}
void unite(int a, int b){
a = find(a), b = find(b);
if(a == b) return;
if(sz[a] < sz[b]) swap(a, b);
link[b] = a;
sz[a] += sz[b];
}
};
void solve(){
int n; cin >> n;
vvi adj(n+1);
DSU dsu(n);
int root, special;
for(int i=0; i<n; i++){
int u, v; cin >> u >> v;
if(dsu.same(u, v)){
root = u;
special = v;
} else {
dsu.unite(u, v);
adj[u].pb(v); adj[v].pb(u);
}
}
vi par(n+1, -1);
function<void(int)> dfs = [&](int s){
for(auto u:adj[s]){
if(u == par[s]) continue;
par[u] = s;
dfs(u);
}
};
dfs(root);
int dp[n+1][2][2][2][2];
memset(dp, -1, sizeof dp);
function<int(int, int, int, int, int)> solve = [&](int x, int me, int up, int rt, int sp){
if(dp[x][me][up][rt][sp] != -1) return dp[x][me][up][rt][sp];
bool ok = (!(x == root && rt != me) && !(x == special && sp != me) && !(x == special && up && rt));
if(!ok) return dp[x][me][up][rt][sp] = inf;
bool cov = (up || (x == special && rt) || (x == root && sp));
int sum = me;
for(auto u:adj[x])
if(u != par[x]) sum += solve(u, 0, me, rt, sp);
if(cov) return dp[x][me][up][rt][sp] = sum;
else {
int ans = inf;
for(auto u:adj[x])
if(u != par[x]) ans = min(ans,
sum-solve(u, 0, me, rt, sp)+solve(u, 1, me, rt, sp));
return dp[x][me][up][rt][sp] = ans;
}
};
int ans = inf;
for(int rt=0; rt<=1; rt++)
for(int sp=0; sp<=1; sp++)
ans = min(ans, solve(root, rt, 0, rt, sp));
cout << (ans == inf ? -1 : ans) << "\n";
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
// #ifndef ONLINE_JUDGE
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
// #endif
int tt = 1;
// cin >> tt;
while(tt--)
solve();
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... |