#include <bits/stdc++.h>
using namespace std;
#define MAXN 100005
#define FOR(i, a, b) for(int i = a; i <= b; i++)
#define f first
#define s second
int n, ec[MAXN];
string st[MAXN], nx[MAXN];
map<string, int> idx;
set<int> adj[MAXN];
set<pair<int, int>> se;
bool d[MAXN];
int main(){
cin >> n;
FOR(i, 1, n) ec[i] = 0;
FOR(i, 1, n){
cin >> st[i];
idx.insert({st[i], i});
cin >> nx[i];
}
if(n % 2) {
cout << -1 << endl;
return 0;
}
int r = 0;
FOR(i, 1, n){
d[i] = (idx[nx[idx[nx[i]]]] == i && idx[nx[i]] != i);
}
FOR(i, 1, n){
if(i == idx[nx[i]] || d[i] || d[idx[nx[i]]]) continue;
adj[i].insert(idx[nx[i]]);
adj[idx[nx[i]]].insert(i);
}
FOR(i, 1, n) if(!d[i]) se.insert({adj[i].size(), i});
while(se.size()){
auto si = *se.begin();
if(si.f == 0){
r++;
}else{
int j = 0, jmn = INT_MAX;
for(int i : adj[si.s]){
if(jmn > ec[i]) j = i, jmn = ec[i];
}
r++;
se.erase({jmn, j});
for(int j2 : adj[j]){
se.erase({ec[j2], j2});
adj[j2].erase(j), ec[j2]--;
se.insert({ec[j2], j2});
}
}
for(int i2 : adj[si.s]) {
se.erase({ec[i2], i2});
adj[i2].erase(si.s), ec[i2]--;
se.insert({ec[i2], i2});
}
se.erase(se.begin());
}
cout << r << endl;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
2063 ms |
11356 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
4 ms |
11356 KB |
Output is correct |
2 |
Correct |
4 ms |
11356 KB |
Output is correct |
3 |
Execution timed out |
2070 ms |
11356 KB |
Time limit exceeded |
4 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
2059 ms |
33616 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
2063 ms |
11356 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |