1
0

HYSBZ-2212.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. struct Node { int left = 0, right = 0, count = 0; };
  5. int main() {
  6. ios::sync_with_stdio(false); cin.tie(nullptr);
  7. int n; cin >> n;
  8. vector<int> token(2 * n - 1); for (int &x : token) cin >> x;
  9. vector<Node> tree(1); tree.reserve(static_cast<size_t>(n) * 20);
  10. auto insert = [&](auto &&self, int l, int r, int position) -> int {
  11. int u = tree.size(); tree.push_back({}); tree[u].count = 1;
  12. if (l < r) { int mid = (l + r) / 2; if (position <= mid) tree[u].left = self(self, l, mid, position); else tree[u].right = self(self, mid + 1, r, position); }
  13. return u;
  14. };
  15. auto merge = [&](auto &&self, int a, int b, int l, int r, long long &normal, long long &swapped) -> int {
  16. if (!a) return b; if (!b) return a;
  17. if (l < r) {
  18. normal += 1LL * tree[tree[a].right].count * tree[tree[b].left].count;
  19. swapped += 1LL * tree[tree[b].right].count * tree[tree[a].left].count;
  20. int mid = (l + r) / 2;
  21. tree[a].left = self(self, tree[a].left, tree[b].left, l, mid, normal, swapped);
  22. tree[a].right = self(self, tree[a].right, tree[b].right, mid + 1, r, normal, swapped);
  23. }
  24. tree[a].count += tree[b].count; return a;
  25. };
  26. vector<int> stack; long long answer = 0;
  27. for (int i = static_cast<int>(token.size()) - 1; i >= 0; --i) {
  28. if (token[i] != 0) stack.push_back(insert(insert, 1, n, token[i]));
  29. else {
  30. int left = stack.back(); stack.pop_back(); int right = stack.back(); stack.pop_back();
  31. long long normal = 0, swapped = 0;
  32. stack.push_back(merge(merge, left, right, 1, n, normal, swapped));
  33. answer += min(normal, swapped);
  34. }
  35. }
  36. cout << answer << '\n';
  37. }