//*** Bismillah ***//
#pragma GCC optimize("O3", "fast-math", "unroll-loops", "no-stack-protector")
#include <bits/stdc++.h>
using namespace std;
#if !defined(ONLINE_JUDGE) and !defined(EVAL)
#include "template/debug.h"
#else
#define d(x...)
#endif
#define fr first
#define er erase
#define sc second
#define in insert
#define ll long long
#define pb push_back
#define vll vector<ll>
#define pll pair<ll,ll>
#define ull unsigned ll
#define vpll vector<pll>
#define len(x) (ll) x.size()
#define all(x) x.begin(),x.end()
const ll INF = 1e9;
const ll INFL = 1e18;
const ll MOD = 1e9+7;
// const ll MOD = 998244353;
const ll maxn = 1e5+5;
ll n,m,k=0;
vll g[maxn];
ll col[maxn], leaf;
queue<pll>q;
void bfs(){
ll tmp = col[leaf];
while(!q.empty()){
auto [u, f] = q.front();
q.pop();
f = (f + 1) % 4;
for(auto v : g[u]){
if(col[v] != -1) continue;
col[v] = (f == 1 or f == 2);
if(f == 1 or f == 2) tmp ++;
q.push({v, f});
}
}
for(ll i = 1; i <= n; i ++){
ll say = 0;
for(auto v : g[i]){
if(col[v] == 1) say ++;
if(say > 1) break;
}
if(say != 1) return;
}
k = min(k, tmp);
}
void _(ll &tt){
cin >> n;
for(ll i = 1, a, b; i <= n; i ++){
cin >> a >> b;
g[a].pb(b);
g[b].pb(a);
}
leaf = -1;
for(ll i = 1; i <= n; i ++){
if(len(g[i]) == 1){
leaf = i;
break;
}
}
if(leaf == -1){
cout << (n % 4 == 0 ? n / 2 : -1) << '\n';
return;
}
k = INF;
memset(col, -1, sizeof(col));
q.push({leaf, 0});
col[leaf] = 0;
bfs();
// for(ll i = 1; i <= n; i ++) cout << col[i] << ' '; cout << '\n';
memset(col, -1, sizeof(col));
q.push({leaf, 1});
col[leaf] = 1;
bfs();
// for(ll i = 1; i <= n; i ++) cout << col[i] << ' '; cout << '\n';
if(k == INF) cout << -1 << '\n';
else cout << k << '\n';
}
signed main() {
ll tm = clock();
cin.tie(0)->sync_with_stdio(0);
ll t = 1;
// cin >> t;
for(ll tt = 1; tt <= t; tt ++) {
_(tt);
}
cerr << "\n\033[1;31mTime: \033[1;30m" \
<< (double)(clock()-tm)/1000000 << "\033[1;32m seconds\n";
}
# | 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... |