#include <bits/stdc++.h>
#define ll long long
using namespace std;
#define pii pair<ll, ll>
ll oo = 1e9 + 9;
int n, m, k;
const int MAX = 4e5 + 5, MOD = 1e9 + 7, LOGMAX = 25;
vector<int> g[MAX];
map<string, int> mp;
int par[MAX];
bool vis[MAX];
int sub[MAX];
int dp[MAX][2];
void dfs(int node, int p){
sub[node] = 1;
vis[node] = 1;
int sum = 0;
for(int to : g[node]){
if(p == to) continue;
dfs(to, node);
sub[node] += sub[to];
sum += dp[to][0];
}
dp[node][1] = sum + 1;
for(int to : g[node]){
if(p == to) continue;
dp[node][0] = max(dp[to][1] + (sum - dp[to][0]), dp[node][0]);
}
}
int p[MAX];
int get(int node){
if(p[node] < 0) return node;
return p[node] = get(p[node]);
}
void unite(int u, int v){
u = get(u);
v = get(v);
if(u == v) return;
if(-p[u] < -p[v]) swap(u, v);
p[u] += p[v];
p[v] = u;
}
void solve(){
memset(p, -1, sizeof(p));
cin >> n;
int c = 1;
for(int i = 1; i <= n; i++){
string a, b; cin >> a >> b;
if(!mp[a]) mp[a] = c++;
if(!mp[b]) mp[b] = c++;
unite(mp[a], mp[b]);
g[mp[b]].push_back(mp[a]);
par[mp[a]] = mp[b];
}
if(n & 1){
cout << "-1\n";
return;
}
bool b = 1;
for(int i = 1; i <= n; i++){
if(g[i].empty()) b = false;
}
if(b){
int sum = 0;
for(int i = 1; i <= n; i++){
if(p[i] < 0){
sum += (-p[i] + 1) / 2;
}
}
cout << sum << '\n';
return;
}
int ans = 0;
for(int i = 1; i <= n; i++){
if(par[i] == i){
dfs(i, i);
ans += sub[i] - dp[i][0];
}
}
cout << ans << '\n';
}
signed main(){
int t = 1;
for(int i = 1; i <= t; i++){
solve();
}
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
3 ms |
15964 KB |
Output is correct |
2 |
Correct |
3 ms |
15964 KB |
Output is correct |
3 |
Correct |
3 ms |
15964 KB |
Output is correct |
4 |
Incorrect |
3 ms |
13916 KB |
Output isn't correct |
5 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
3 ms |
13916 KB |
Output is correct |
2 |
Incorrect |
3 ms |
13748 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
278 ms |
30292 KB |
Output is correct |
2 |
Correct |
294 ms |
32592 KB |
Output is correct |
3 |
Correct |
234 ms |
26964 KB |
Output is correct |
4 |
Correct |
288 ms |
25328 KB |
Output is correct |
5 |
Correct |
291 ms |
39760 KB |
Output is correct |
6 |
Correct |
309 ms |
29520 KB |
Output is correct |
7 |
Correct |
266 ms |
29520 KB |
Output is correct |
8 |
Correct |
246 ms |
29780 KB |
Output is correct |
9 |
Correct |
240 ms |
29008 KB |
Output is correct |
10 |
Correct |
186 ms |
28356 KB |
Output is correct |
11 |
Correct |
3 ms |
15960 KB |
Output is correct |
12 |
Correct |
3 ms |
16000 KB |
Output is correct |
13 |
Correct |
4 ms |
15964 KB |
Output is correct |
14 |
Correct |
4 ms |
15960 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
3 ms |
15964 KB |
Output is correct |
2 |
Correct |
3 ms |
15964 KB |
Output is correct |
3 |
Correct |
3 ms |
15964 KB |
Output is correct |
4 |
Incorrect |
3 ms |
13916 KB |
Output isn't correct |
5 |
Halted |
0 ms |
0 KB |
- |