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 int long long
#define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
using namespace std;
const int N = 1e5+5;
int visited[N], arr[N], sz[N], dp[N][2], col[N], ok[N];
vector<int> adj[N];
void dfs(int u, int p){
visited[u] = 1;
sz[u] = 1;
int sum = 0;
for(auto v : adj[u]){
if(v==p || visited[v]) continue;
dfs(v,u);
sum += dp[v][0];
sz[u] += sz[v];
}
dp[u][1] = sum+1;
int mx = 0;
for(auto v : adj[u]){
if(v==p) continue;
mx = max(dp[v][1]-dp[v][0],mx);
}
dp[u][0] = mx+dp[u][1]-1;
}
int idx;
map<string,int> m;
int assign(string x){
if(m.find(x)==m.end()){
m[x] = idx++;
}
return m[x];
}
signed main(){
fastio
int n;
cin >> n;
for(int i = 0;i < n;i++){
string a,b;
cin >> a >> b;
int x = assign(a);
int y = assign(b);
arr[x] = y;
if(x==y) continue;
adj[x].push_back(y);
adj[y].push_back(x);
}
if(n%2){
cout << -1 << "\n";
return 0;
}
for(int i = 0; i < n; i++){
if(arr[arr[i]]==i){
if(adj[arr[i]].size()==2){
ok[i] = 1;
visited[arr[i]] = 1;
}else{
ok[arr[i]] = 1;
visited[i] = 1;
}
}
}
int ans = 0;
for(int i = 0; i < n; i++){
if(arr[i]==i){
dfs(i,i);
ans += sz[i]-dp[i][0];
}
}
for(int i = 0; i < n; i++){
if(!visited[i]){
dfs(i,i);
if(ok[i]){
ans += sz[i]-dp[i][1];
}else{
ans += sz[i]-max(dp[i][0],dp[i][1]);
}
}
}
cout << ans << "\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... |