Advertisement
KiK0S

C regional

Jan 28th, 2019
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <cmath>
  5. #include <cassert>
  6. #include <set>
  7. #include <cstring>
  8. #include <map>
  9. #include <unordered_set>
  10. #include <unordered_map>
  11. #include <bitset>
  12. #include <fstream>
  13.  
  14. using namespace std;
  15. typedef long long ll;
  16.  
  17. #ifdef DEBUG
  18.     const int MAXN = 10;
  19.     const int MAXLOG = 4;
  20.     const int MAXSQRT = 7;
  21. #else
  22.     const int MAXN = 3e5 + 100;
  23.     const int MAXLOG = 20;
  24.     const int MAXSQRT = 400;
  25. #endif
  26.  
  27. int n;
  28. int to[MAXN];
  29. int cnt[MAXN];
  30. int used[MAXN];
  31.  
  32. void init() {
  33.     memset(to, -1, sizeof(to));
  34.     memset(cnt, 0, sizeof(cnt));
  35. }
  36.  
  37. void solve() {
  38.     init();
  39.     for (int i = 0; i < n; i++) {
  40.         int a;
  41.         cin >> a;
  42.         if (a == -1) {
  43.             continue;
  44.         }
  45.         a--;
  46.         to[i] = a;
  47.         cnt[a]++;
  48.     }
  49.     set<pair<int, int>> all;
  50.     for (int i = 0; i < n; i++) {
  51.         all.insert(make_pair(cnt[i], i));
  52.     }
  53.     int ans = 0;
  54.     while (all.size() && (*all.begin()).first == 0) {
  55.         int v = (*all.begin()).second;
  56.         all.erase(*all.begin());
  57.         used[v] = 1;
  58.         ans++;
  59.         if (to[v] != -1) {
  60.             used[to[v]] = 1;
  61.             if (all.count(make_pair(cnt[to[v]], to[v]))) {
  62.                 all.erase(make_pair(cnt[to[v]], to[v]));
  63.                 if (to[to[v]] != -1) {
  64.                     if (all.count(make_pair(cnt[to[to[v]]], to[to[v]]))) {
  65.                         all.erase(make_pair(cnt[to[to[v]]], to[to[v]]));
  66.                         cnt[to[to[v]]]--;
  67.                         all.insert(make_pair(cnt[to[to[v]]], to[to[v]]));
  68.                     }
  69.                 }
  70.             }
  71.         }
  72.     }
  73.     int cur = 0;
  74.     for (int i = 0; i < n; i++) {
  75.         int v = i;
  76.         while (v != -1 && !used[v]) {
  77.             used[v] = 1;
  78.             cur++;
  79.             v = to[v];
  80.         }
  81.         ans += (cur) / 2;
  82.         cur = 0;
  83.     }
  84.     cout << ans << '\n';
  85. }
  86.  
  87. signed main() {
  88.     #ifdef DEBUG
  89.         freopen("C.in", "r", stdin);
  90.         freopen("C.out", "w", stdout);
  91.     #endif
  92.     ios_base::sync_with_stdio(0);
  93.     cin.tie(0);
  94.     cout.tie(0);
  95.     while (cin >> n) {
  96.         solve();
  97.     }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement