fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. using ll = long long;
  5.  
  6. template<class T>
  7. bool Min(T &a, const T &b) {
  8. return a > b ? a = b, 1 : 0;
  9. }
  10.  
  11. const int N = 2e5+5;
  12.  
  13. int n, a[N], b[N];
  14. ll P[N], M[N];
  15.  
  16. void solve() {
  17. cin >> n;
  18. for (int i = 0; i < n; i++) cin >> a[i];
  19.  
  20. ll sum = 0, mn = 0;
  21. int idx = 0;
  22. for (int i = 0; i < n; i++) {
  23. sum += a[i];
  24. if (Min(mn, sum)) idx = i + 1;
  25. }
  26. idx %= n;
  27.  
  28. for (int i = 0; i < n; i++)
  29. b[i] = a[(idx + i) % n];
  30.  
  31. for (int i = 1; i < n; i++) {
  32. P[i] = P[i - 1] + max(0, b[i - 1]);
  33. M[i] = M[i - 1] + min(0, b[i - 1]);
  34. }
  35.  
  36. ll ans = 0; int v = 0;
  37. for (int u = 0; u < n; u++) {
  38. while (v < n && -M[v] < P[u]) v++;
  39. ans += (n - max(u, v));
  40. }
  41. cout << ans << '\n';
  42. }
  43.  
  44. int main() {
  45. ios_base::sync_with_stdio(false); cin.tie(NULL);
  46.  
  47. int tests = 1; cin >> tests;
  48. while (tests--) solve();
  49.  
  50. #ifndef ONLINE_JUDGE
  51. cerr << "\nTime elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
  52. #endif
  53.  
  54. return 0;
  55. }
  56.  
Success #stdin #stdout 0s 5688KB
stdin
5
2
1 -1
3
-2 1 1
5
5 -3 6 -7 -1
8
3 -5 2 -4 6 -1 -3 2
13
4 -2 -3 7 -6 1 -5 8 -4 2 -1 -3 2
stdout
2
3
7
16
54