nq1s788

Сумма НУП

Nov 2nd, 2025
632
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. Let 𝑖1,…,𝑖𝑚
  2.  be the set of 𝑖∈[1,𝑛]
  3.  such that 𝑎𝑖>𝑎𝑖+1
  4. . Let us show that the sequence (𝑖1,…,𝑖𝑚)
  5.  is an LDS:
  6.  
  7. It is a decreasing subsequence: let 𝑘∈[1,𝑚−1]
  8. . If 𝑖𝑘+1=𝑖𝑘+1
  9. , then 𝑎𝑖𝑘>𝑎(𝑖𝑘)+1=𝑎𝑖𝑘+1
  10. . Else, we have 𝑎(𝑖𝑘)+2<max(𝑎𝑖𝑘,𝑎(𝑖𝑘)+1)
  11. , but 𝑖𝑘+1
  12.  is such that 𝑎𝑖𝑘+2≥𝑎𝑖𝑘+1
  13. , so 𝑎(𝑖𝑘)+2<𝑎𝑖𝑘
  14. . We have also 𝑎𝑖𝑘+1<𝑎𝑖𝑘
  15.  by definition so we can easily prove by induction on 𝑗>0
  16.  that 𝑎𝑖𝑘+𝑗<𝑎𝑖𝑘
  17.  where it makes sense.
  18. It's optimal : let 𝐸
  19. be the set of indexes taken by a LDS. For each i such that 𝑎𝑖≤𝑎𝑖+1
  20. , at least one of the elements of 𝑖,𝑖+1
  21. does not belong to 𝐸
  22. . Now, these sets are disjoint : if 𝑎𝑖<𝑎𝑖+1
  23. we cannot have 𝑎𝑖+2<𝑎𝑖+1
  24. (otherwise the condition max(𝑎𝑖,𝑎𝑖+1)>𝑎𝑖+2
  25. is not met. So |𝐸|≤𝑚
  26. .
  27. To calculate the sum of the LDS of the sub-arrays, it is therefore sufficient to count for each 𝑖
  28. such that 𝑎𝑖<𝑎𝑖+1
  29. the number of sub-arrays 𝑎[𝑙,𝑟]
  30. which contain 𝑖
  31. and 𝑖+1
  32. . It's (𝑖+1)⋅(𝑛−𝑖−1)
  33.  for 0
  34. -indexation : a necessary and sufficient condition is that 𝑙≤𝑖
  35.  and 𝑟≥𝑖+1
  36. .
  37.  
  38. Note that there also exists a dp approach
  39.  
  40. #include <bits/stdc++.h>
  41. #define int long long
  42. using namespace std;
  43.  
  44. signed main() {
  45.     ios::sync_with_stdio(false), cin.tie(0);
  46.     int nTests; cin >> nTests;
  47.  
  48.     while (nTests--) {
  49.         int nVals; cin >> nVals;
  50.         vector<int> vals(nVals);
  51.        
  52.         for (int& val : vals)
  53.             cin >> val;
  54.  
  55.         int sum = (nVals * (nVals + 1) * (nVals + 2))/6;
  56.         for (int i = 0; i + 1 < nVals; ++i) {
  57.             if (vals[i] < vals[i + 1]) {
  58.                 sum -= (i + 1) * (nVals - i - 1);
  59.             }
  60.         }
  61.  
  62.         cout << sum << endl;
  63.     }
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment