fork download
  1. #include <bits/stdc++.h>
  2. #define int long long
  3.  
  4. using namespace std;
  5.  
  6. const int MOD = 1e9 + 7;
  7.  
  8. void solve(){
  9. int n;
  10. cin >> n;
  11. vector<int> a(n);
  12. int ma = 0, mi = LLONG_MAX;
  13.  
  14. for(int i = 0; i < n; i++){
  15. cin >> a[i];
  16. ma = max(ma, a[i]);
  17. mi = min(mi, a[i]);
  18. }
  19. vector<int> tmp(a.begin(), a.end());
  20.  
  21. int s = mi, e = ma;
  22. int ans = ma - mi;
  23. while(s <= e){
  24. int mid = s + (e - s) / 2;
  25. vector<pair<int,int>> cnt;
  26. int mi1 = LLONG_MAX;
  27. vector<int> b(a.begin(), a.end());
  28.  
  29. for(int i = 0; i < n; i++){
  30. if(b[i] > mid){
  31. cnt.push_back({b[i] - mid, i});
  32. b[i] = mid;
  33. }
  34. while(b[i] < mid && cnt.size()){
  35. if(cnt.back().first + b[i] > mid){
  36. cnt.back().first -= mid - b[i];
  37. b[i] = mid;
  38. break;
  39. }else{
  40. b[i] += cnt.back().first;
  41. cnt.pop_back();
  42. }
  43. }
  44. mi1 = min(mi1, b[i]);
  45.  
  46. }
  47.  
  48. if(cnt.size()){
  49. s = mid + 1;
  50. }else{
  51.  
  52. ma = min(ma, mid);
  53. tmp = b;
  54. e = mid - 1;
  55. }
  56.  
  57. }
  58.  
  59. int ss = mi, ee = ma;
  60.  
  61.  
  62. while(ss <= ee){
  63. int midd = ss + (ee - ss) / 2;
  64. vector<int> b(tmp.begin(), tmp.end());
  65. int idx = -1;
  66. bool pos = true;
  67. for(int i = 0; i < n; i++)if(b[i] >= ma)idx = i;
  68. vector<pair<int, int>> ext;
  69.  
  70. for(int i = 0; i< n && pos; i++){
  71. if(i == idx){
  72. if(b[i] > ma){
  73. ext.push_back({b[i] - ma, i});
  74. }
  75. continue;
  76. }
  77. if(b[i] > midd){
  78. ext.push_back({b[i] - midd, i});
  79. b[i] = midd;
  80. }
  81. while(b[i] < midd && ext.size()){
  82. if(ext.back().first + b[i] > midd){
  83. ext.back().first -= midd - b[i];
  84. b[i] = midd;
  85. }else{
  86. b[i] += ext.back().first;
  87. ext.pop_back();
  88. }
  89. }
  90. if(b[i] < midd)pos = false;
  91. }
  92.  
  93. if(pos && (!ext.size() || ext.back().second != idx)){
  94. mi = max(mi, midd);
  95. ss = midd + 1;
  96. }else{
  97. ee = midd - 1;
  98. }
  99. }
  100.  
  101. cout << ma - mi << "\n";
  102. }
  103.  
  104. int32_t main(){
  105. ios_base::sync_with_stdio(false);
  106. cin.tie(nullptr);
  107.  
  108. int t = 1;
  109. cin >> t;
  110.  
  111. for(int i = 1; i <= t; i++){
  112. solve();
  113. }
  114. return 0;
  115. }
Success #stdin #stdout 0.01s 5288KB
stdin
5
1
1
3
1 2 3
4
4 1 2 3
4
4 2 3 1
5
5 14 4 10 2
stdout
0
2
1
1
3