intquery(int left, int right)const{ returnquery_(0, 1, n, left, right); } };
classSolution { private: staticconstexprint mod = 1000000007;
public: intcreateSortedArray(vector<int>& instructions){ int ub = *max_element(instructions.begin(), instructions.end()); SegTree tree(ub); longlong ans = 0; for (int i = 0; i < instructions.size(); ++i) { int x = instructions[i]; int smaller = tree.query(1, x - 1); int larger = tree.query(x + 1, ub); ans += min(smaller, larger); tree.update(x); } return ans % mod; } };
staticconstexprintlowbit(int x){ return x & (-x); } voidupdate(int x){ while (x <= n) { ++tree[x]; x += lowbit(x); } }
intquery(int x)const{ int ans = 0; while (x) { ans += tree[x]; x -= lowbit(x); } return ans; } };
classSolution { private: staticconstexprint mod = 1000000007;
public: intcreateSortedArray(vector<int>& instructions){ int ub = *max_element(instructions.begin(), instructions.end()); BIT bit(ub); longlong ans = 0; for (int i = 0; i < instructions.size(); ++i) { int x = instructions[i]; int smaller = bit.query(x - 1); int larger = i - bit.query(x); ans += min(smaller, larger); bit.update(x); } return ans % mod; } };
intlower_bound(int x)const{ BalancedNode* node = root; int ans = INT_MAX; while (node) { if (x == node->val) { return x; } if (x < node->val) { ans = node->val; node = node->left; } else { node = node->right; } } return ans; }
intupper_bound(int x)const{ BalancedNode* node = root; int ans = INT_MAX; while (node) { if (x < node->val) { ans = node->val; node = node->left; } else { node = node->right; } } return ans; }
pair<int, int> rank(int x)const{ BalancedNode* node = root; int ans = 0; while (node) { if (x < node->val) { node = node->left; } else { ans += (node->left ? node->left->size : 0) + node->count; if (x == node->val) { return {ans - node->count + 1, ans}; } node = node->right; } } return {INT_MIN, INT_MAX}; } };
classSolution { private: staticconstexprint mod = 1000000007;
public: intcreateSortedArray(vector<int>& instructions){ BalancedTree treap; longlong ans = 0; for (int i = 0; i < instructions.size(); ++i) { int x = instructions[i]; int lb = treap.lower_bound(x); int smaller = (lb == INT_MAX ? i : treap.rank(lb).first - 1); int rb = treap.upper_bound(x); int larger = (rb == INT_MAX ? 0 : i - treap.rank(rb).first + 1); ans += min(smaller, larger); treap.insert(x); } return ans % mod; } };