大厂笔试题
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
926 B

  1. /*求区间众数和
  2. nn个正整数1<n<200000,1<=a<=2
  3. 3
  4. 2 1 2
  5. 9
  6. */
  7. #include <cstdio>
  8. #include <iostream>
  9. #include <algorithm>
  10. typedef long long LL;
  11. const int N = 200010;
  12. int n;
  13. int a[N], tr[N * 2];
  14. int sum[N];
  15. int lowbit(int x) {
  16. return x & -x;
  17. }
  18. void modify(int x, int k) {
  19. for (int i = x; i <= 2 * n + 5; i += lowbit(i)) tr[i] += k;
  20. }
  21. int query(int x) {
  22. int res = 0;
  23. for (int i = x; i; i -= lowbit(i)) res += tr[i];
  24. return res;
  25. }
  26. int main() {
  27. scanf("%d", &n);
  28. for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  29. LL ans = 0;
  30. modify(0 + n + 1, 1);
  31. for (int i = 1; i <= n; i++) {
  32. sum[i] = sum[i - 1];
  33. if (a[i] == 1) sum[i] += 1;
  34. else sum[i] -= 1;
  35. ans += query(sum[i] + n + 1) + (i - query(sum[i] + n + 1)) * 2;
  36. modify(sum[i] + n + 1, 1);
  37. }
  38. printf("%lld", ans);
  39. return 0;
  40. }