Submission #488904

#TimeUsernameProblemLanguageResultExecution timeMemory
488904VictorLogičari (COCI21_logicari)C++17
110 / 110
211 ms27312 KiB
#include <bits/stdc++.h> using namespace std; #define rep(i, a, b) for (int i = (a); i < (b); ++i) #define per(i, a, b) for (int i = (b - 1); i >= (a); --i) #define trav(a, x) for (auto &a : x) #define all(x) x.begin(), x.end() #define sz(x) x.size() #define pb push_back #define debug(x) cout << #x << " = " << x << endl #define umap unordered_map #define uset unordered_set typedef pair<int, int> ii; typedef pair<int, ii> iii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<vi> vvi; typedef long long ll; typedef pair<ll, ll> pll; typedef vector<ll> vll; typedef vector<pll> vpll; const int INF = 1'000'000'007; struct union_find { vi p, rank; union_find(int n) { p.resize(n); rep(i, 0, n) p[i] = i; rank.assign(n, 0); } int find(int i) { return p[i] == i ? i : p[i] = find(p[i]); } bool same(int i, int j) { return find(i) == find(j); } void union_set(int i, int j) { i = find(i); j = find(j); if (i == j) return; if (rank[i] < rank[j]) swap(i, j); p[j] = i; if (rank[i] == rank[j]) ++rank[i]; } }; vi graph[100001]; int root, rem, memo[100001][2][2][2][2], dfs_parent[100001]; int dp(int u, bool take_cur, bool parent, bool taken, bool root_taken) { if (u == rem) { if (taken != take_cur) return INF; if (root_taken && parent) return INF; } int &ans = memo[u][take_cur][parent][taken][root_taken]; if (ans != -1) return ans; if(u==rem)parent |= root_taken; ans = 0; int cnt = 0; ll mn = INF,cur_ans=0; trav(v, graph[u]) if (v != dfs_parent[u]) { dfs_parent[v]=u; ++cnt; ll val = dp(v, 0, take_cur, taken, root_taken); cur_ans+=val; if (!parent) { ll diff = dp(v,1,take_cur,taken,root_taken)-val; mn=min(mn,diff); } } if(!parent&&!cnt)return ans= INF; if(!parent)ans=min((ll)INF,cur_ans+mn); else ans=min((ll)INF,cur_ans); //cout<<"u = "<<u+1<<" take_cur = "<<take_cur<<" parent = "<<parent<<" ans = "<<ans<<endl; return ans+take_cur; } int main() { cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); memset(memo, -1, sizeof(memo)); int n; cin >> n; union_find ufds(n); rep(i, 0, n) { int u, v; cin >> u >> v; if (ufds.same(--u, --v)) { root = u; rem = v; continue; } graph[u].pb(v); graph[v].pb(u); ufds.union_set(u, v); } dfs_parent[root] = root; int ans = INF; ans = dp(root, 1, 0, 0, 1); ans = min(ans, dp(root, 1, 1, 1, 1)); ans = min(ans, dp(root, 0, 0, 0, 0)); ans = min(ans, dp(root, 0, 1, 1, 0)); if (ans > n) ans = -1; cout << ans << endl; return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...