이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
const int MX = 2e5 + 10;
struct dsu{
int p[MX], cc[MX];
void init(){
for(int i = 0; i < MX; i++) p[i] = i, cc[i] = 1;
}
int f(int x){
if(p[x] == x) return x;
else return p[x] = f(p[x]);
}
void Join(int u, int v){
int fu = f(u), fv = f(v);
if(fu == fv) return;
p[fu] = fv;
cc[fv] += cc[fu];
}
} D;
int N, a[MX], b[MX], nx[MX], degree[MX], vis[MX], tim = 0;
map<string, int> mp;
bool dead[MX];
int dfs(int x){
if(vis[x]) return 0;
vis[x] = true;
return 1 + dfs(nx[x]);
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int ans = 0;
cin >> N;
for(int i = 0; i < N; i++){
string s, t; cin >> s >> t;
if(!mp.count(s)) mp[s] = ++tim;
if(!mp.count(t)) mp[t] = ++tim;
a[i] = mp[s], b[i] = mp[t];
nx[a[i]] = b[i];
degree[b[i]]++;
if(nx[b[i]] == a[i] && a[i] != b[i]){
vis[a[i]] = true;
vis[b[i]] = true;
}
}
if(N % 2 == 1){
cout << -1 << '\n';
return 0;
}
vector<int> qsolve;
for(int i = 1; i <= N; i++){
if(degree[i] == 0) qsolve.push_back(i);
}
for(; !qsolve.empty(); ){
int st = qsolve.back(); qsolve.pop_back();
if(vis[st] || vis[nx[st]]) continue;
ans++;
vis[st] = 1;
vis[nx[st]] = 1;
degree[nx[st]]--;
if(nx[nx[st]] == nx[st]) continue;
if(!vis[nx[nx[st]]] && degree[nx[nx[st]]] == 1){
degree[nx[nx[st]]]--;
qsolve.push_back(nx[nx[st]]);
}
}
for(int i = 1; i <= N; i++){
if(vis[i]) continue;
int curr_sz = dfs(i);
ans += (curr_sz + 1) / 2;
}
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... |