Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <cmath>
- #include <cassert>
- #include <set>
- #include <cstring>
- #include <map>
- #include <unordered_set>
- #include <unordered_map>
- #include <bitset>
- #include <fstream>
- using namespace std;
- typedef long long ll;
- #ifdef DEBUG
- const int MAXN = 10;
- const int MAXLOG = 4;
- const int MAXSQRT = 7;
- #else
- const int MAXN = 3e5 + 100;
- const int MAXLOG = 20;
- const int MAXSQRT = 400;
- #endif
- int n;
- int to[MAXN];
- int cnt[MAXN];
- int used[MAXN];
- void init() {
- memset(to, -1, sizeof(to));
- memset(cnt, 0, sizeof(cnt));
- }
- void solve() {
- init();
- for (int i = 0; i < n; i++) {
- int a;
- cin >> a;
- if (a == -1) {
- continue;
- }
- a--;
- to[i] = a;
- cnt[a]++;
- }
- set<pair<int, int>> all;
- for (int i = 0; i < n; i++) {
- all.insert(make_pair(cnt[i], i));
- }
- int ans = 0;
- while (all.size() && (*all.begin()).first == 0) {
- int v = (*all.begin()).second;
- all.erase(*all.begin());
- used[v] = 1;
- ans++;
- if (to[v] != -1) {
- used[to[v]] = 1;
- if (all.count(make_pair(cnt[to[v]], to[v]))) {
- all.erase(make_pair(cnt[to[v]], to[v]));
- if (to[to[v]] != -1) {
- if (all.count(make_pair(cnt[to[to[v]]], to[to[v]]))) {
- all.erase(make_pair(cnt[to[to[v]]], to[to[v]]));
- cnt[to[to[v]]]--;
- all.insert(make_pair(cnt[to[to[v]]], to[to[v]]));
- }
- }
- }
- }
- }
- int cur = 0;
- for (int i = 0; i < n; i++) {
- int v = i;
- while (v != -1 && !used[v]) {
- used[v] = 1;
- cur++;
- v = to[v];
- }
- ans += (cur) / 2;
- cur = 0;
- }
- cout << ans << '\n';
- }
- signed main() {
- #ifdef DEBUG
- freopen("C.in", "r", stdin);
- freopen("C.out", "w", stdout);
- #endif
- ios_base::sync_with_stdio(0);
- cin.tie(0);
- cout.tie(0);
- while (cin >> n) {
- solve();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement