AlexNeagu11

SumeSecv

Mar 19th, 2022
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int nmax = 100006;
  4. int block[nmax], blockSize, a[nmax], N, M;
  5. long long sumByBlock[nmax];
  6.  
  7. long long getSum(int L, int R) {
  8. long long ans = 0;
  9. while(L < R && block[L] == block[L + 1]) {
  10. ans += a[L];
  11. L++;
  12. }
  13. while(R > L && block[R] == block[R - 1]) {
  14. ans += a[R];
  15. R--;
  16. }
  17. if(L == R) {
  18. ans += a[L];
  19. L++;
  20. } else {
  21. ans += a[L];
  22. ans += a[R];
  23. L++;
  24. R--;
  25. }
  26. if(L <= R) {
  27. for(int j = block[L]; j <= block[R]; ++j) {
  28. ans += sumByBlock[j];
  29. }
  30. }
  31. return ans;
  32. }
  33.  
  34. void updatePos(int pos, int x) {
  35. int whatBlock = block[pos];
  36. sumByBlock[whatBlock] -= a[pos];
  37. a[pos] = x;
  38. sumByBlock[whatBlock] += a[pos];
  39. }
  40.  
  41. int main() {
  42. cin >> N;
  43. for(int i = 0; i < N; ++i) {
  44. cin >> a[i];
  45. }
  46. blockSize = (int) sqrt(N);
  47. for(int i = 0; i < N; ++i) {
  48. block[i] = i / blockSize;
  49. }
  50. for(int i = 0; i < N; ++i) {
  51. int whatBlock = block[i];
  52. sumByBlock[whatBlock] += a[i];
  53. }
  54. cin >> M;
  55. long long ans = -2e18;
  56. for(int i = 0; i < M; ++i) {
  57. int L, R;
  58. cin >> L >> R;
  59. if(L > R) {
  60. swap(L, R);
  61. }
  62. ans = max(ans, getSum(L - 1, R - 1));
  63. }
  64. cout << ans << '\n';
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment