#include <bits/stdc++.h>
#define pb push_back
#define ll long long
#define vll vector <ll>
#define vbool vector<bool>
#define pairll pair<ll,ll>
#define fi first
#define sc second
#define rever greater<ll>()
using namespace std;
bool dfs(vector<vll> &path, vll &col, ll x, ll prev, ll k){
//cout << x << ' ' << prev << ' ' << k << endl;
k++;
//cout << x << ' ' << prev << ' ' << k << endl;
if(col[x] == 0)col[x] = k;
else if(col[x] != k)return false;
else return true;
for(ll i : path[x]){
if(i == prev)continue;
//cout << i <<',';
if(col[i] == 0)col[i] = k;
else if(col[i] != k)return false;
else return true;
//cout << i << ' ';
for(ll j : path[i]){
if(j == x)continue;
if(!dfs(path, col, j, i, k%2))return false;
}
}cout << endl;
return true;
}
void solve(){
ll n; cin >> n;
vector<vll> path(n+1);
for(ll i = 0, u, v; i < n; i++){
cin >> u >> v;
path[u].pb(v); path[v].pb(u);
}
ll a = 0, b = 0;
for(ll i = 1; i <= n; i++){
if(path[i].size() == 1){
if(a)b = i;
else a = i;
}
}
if(a == 0){
if(n%4)cout << -1 << endl;
else cout << n/2 << endl;
return;
}
if(a)a = path[a][0];
if(b)b = path[b][0];
ll res = -1;
for(ll i : path[a]){
vll col(n+1); col[a] = col[b] = col[i] = 2;
bool ans = true;
for(ll j : path[a]){
if(j == i)continue;
if(!dfs(path, col, j, a, 0))ans = false;
}
for(ll j : path[i]){
if(j == a)continue;
if(!dfs(path, col, j, i, 0))ans = false;
}
//cout << a << ' ' << i << endl;
//for(ll t = 1; t <= n; t++)cout << col[t] << ' ';
//cout << endl;
if(ans){
ll tot = 0;
for(ll i = 1; i <= n; i++){
if(col[i] == 2)tot++;
}
if(res == -1)res = tot;
else res = min(res, tot);
}
}cout << res << endl;
}
int main(){
ios::sync_with_stdio(false); cin.tie(nullptr);
ll t=1; //cin >> t;
for(int i = 1; i <= t; i++){
solve();
}
}
# | 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... |