結果
問題 | No.956 Number of Unbalanced |
ユーザー |
![]() |
提出日時 | 2020-01-26 00:27:48 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 248 ms / 2,000 ms |
コード長 | 1,878 bytes |
コンパイル時間 | 2,042 ms |
コンパイル使用メモリ | 180,916 KB |
実行使用メモリ | 41,780 KB |
最終ジャッジ日時 | 2024-09-14 04:19:37 |
合計ジャッジ時間 | 6,113 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 6 |
other | AC * 24 |
ソースコード
#include <bits/stdc++.h>int ri() {int n;scanf("%d", &n);return n;}struct BIT {int n;std::vector<int64_t> data;std::vector<int> written;BIT (int n) : n(n), data(n + 1, 0) {}void add(int i, int64_t val) {for (i++; i <= n; i += i & -i) data[i] += val, written.push_back(i);}int64_t sum(int r) {int64_t res = 0;for (; r; r &= r - 1) res += data[r];return res;}void clear() {for (auto i : written) data[i] = 0;written.clear();}};struct BIT2 {int n;BIT tree0, tree1, tree2;BIT2(int n) : n(n), tree0(2 * n + 1), tree1(2 * n + 1), tree2(2 * n + 1) {}void add(int l, int r, int val) {l += n;r += n;tree0.add(l, val);tree1.add(l, -val * l);tree2.add(l, val * ((int64_t) l * (l - 1) / 2));tree0.add(r, -val);tree1.add(r, val * r);tree2.add(r, -val * ((int64_t) l * (l - 1) / 2 + (int64_t) r * (r - l) - (int64_t) (r - l) * (r - l + 1) / 2));}private :int64_t sum1(int r) {return ((int64_t) r * (r + 1) / 2 * tree0.sum(r) + (int64_t) r * tree1.sum(r) + tree2.sum(r));}public :int64_t sum2(int l, int r) {l += n;r += n;return sum1(r) - sum1(l);}void clear() {tree0.clear();tree1.clear();tree2.clear();}};int main() {int n = ri();int a[n];std::map<int, std::vector<int> > indexes;for (int i = 0; i < n; i++) a[i] = ri(), indexes[a[i]].push_back(i);BIT2 tree(n);int64_t res = 0;for (auto &i : indexes) {tree.add(0, 1, 1);int last = 0;int cur = 0;auto process_empty = [&] (int len) {if (!len) return;res += tree.sum2(cur - len - 1, cur - 1);tree.add(cur - len, cur, 1);cur -= len;};for (auto j : i.second) {process_empty(j - last);res += tree.sum2(cur, cur + 1);cur++;tree.add(cur, cur + 1, 1);last = j + 1;}process_empty(n - last);tree.clear();}std::cout << res << std::endl;return 0;}