fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. int t;
  6. cin>>t;
  7. while(t--)
  8. {
  9. int n;
  10. cin>>n;
  11. vector<long long>a;
  12. long long sum=0;
  13. int u=9;
  14. for(int i=0;i<n;i++)
  15. {
  16. long long k;
  17. cin>>k;
  18. a.push_back(k);
  19. sum+=k;
  20. if(sum<0)
  21. u=1;
  22. }
  23. if(u==1)
  24. {
  25. cout<<-1<<endl;
  26. continue;
  27. }
  28. int ans=0;
  29. u=3;
  30. while(u>0)
  31. {
  32. int p=0;
  33. for(int i=0;i<n;i++)
  34. {
  35. if(a[i]<0 && i!=n-1)
  36. {
  37. a[i-1]+=a[i];
  38. a[i+1]+=a[i];
  39. a[i]*=-1;
  40. ans++;
  41. }
  42. else if(a[i]<0)
  43. {
  44. a[i-1]+=a[i];
  45. a[i]*=-1;
  46. ans++;
  47. }
  48. else if(a[i]>=0)
  49. {
  50. p++;
  51. }
  52. }
  53. if(p==n)
  54. break;
  55. }
  56. cout<<ans<<endl;
  57. }
  58. }
Success #stdin #stdout 0s 548KB
stdin
1
5
5 -3 8 -9 10
stdout
4