이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
using namespace std;
const long long inf = (long long) 1e18 + 10;
const int inf1 = (int) 1e9 + 10;
#define int long long
#define dbl long double
#define endl '\n'
#define sc second
#define fr first
#define mp make_pair
#define pb push_back
#define all(x) x.begin(), x.end()
const int maxn = 1e5+10;
int n, nx[maxn], mark[maxn], markc[maxn], dp[maxn][2];
string nxstring[maxn];
vector<int> ginv[maxn];
int dfscyc(int u) {
if(markc[u]) return u;
markc[u] = 1;
return dfscyc(nx[u]);
}
void dfs(int u, int id) {
int mn = inf1;
mark[u] = id;
dp[u][0] = 0;
for(auto v : ginv[u]) {
if(mark[v] == id) continue;
dfs(v,id);
dp[u][0]+= min(dp[v][1],dp[v][0]+1);
mn = min(mn, dp[v][0] - min(dp[v][1],dp[v][0]+1));
if(nx[u] == v) mn = min(mn, dp[v][0]-1 - min(dp[v][1],dp[v][0]+1));
}
dp[u][1] = dp[u][0]+mn+1;
}
void solve() {
cin >> n;
map<string,int> cc;
for(int i = 1; i <= n; i++) {
string s1,s2; cin >> s1 >> s2;
cc[s1] = i;
nxstring[i] = s2;
}
if(n%2 == 1) {
cout << -1 << endl;
return;
}
for(int i = 1; i <= n; i++) {
nx[i] = cc[nxstring[i]];
// cout << i << " " << nx[i] << endl;
ginv[nx[i]].pb(i);
}
int ans = 0;
for(int i = 1; i <= n; i++) {
if(mark[i]) continue;
int rt = dfscyc(i);
// cout << rt << " root " << endl;
dfs(rt,1);
int ans1 = min(dp[rt][1],dp[rt][0]+1);
rt = nx[rt];
dfs(rt,2);
ans1 = min(ans1,min(dp[rt][1],dp[rt][0]+1));
ans+= ans1;
}
cout << ans << endl;
}
int32_t main() {
ios::sync_with_stdio(false); cin.tie(0);
// freopen("in.in", "r", stdin);
// freopen("out.out", "w", stdout);
int tt = 1;
// cin >> tt;
while(tt--) 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... |