Advertisement
coloriot

HA46

Mar 23rd, 2025
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <unordered_map>
  4. using namespace std;
  5.  
  6. class MedianSubsegmentsOptimized {
  7. public:
  8.     void solve() {
  9.         int N, B;
  10.         cin >> N >> B;
  11.         vector<int> permutation(N);
  12.         int pos = -1;
  13.         for (int i = 0; i < N; ++i) {
  14.             cin >> permutation[i];
  15.             if (permutation[i] == B) {
  16.                 pos = i; // Записываем значения нулевых индексов
  17.             }
  18.         }
  19.        
  20.         // Префиксные суммы
  21.         vector<int> prefix(N + 1, 0);
  22.         for (int i = 0; i < N; ++i) {
  23.             int val = 0;
  24.             if (permutation[i] > B) {
  25.                 val = 1;
  26.             } else if (permutation[i] < B) {
  27.                 val = -1;
  28.             }
  29.             prefix[i + 1] = prefix[i] + val;
  30.         }
  31.        
  32.         // Считаем частоту префиксных сумм
  33.         unordered_map<int, long long> freq;
  34.         for (int i = 0; i <= pos; ++i) {
  35.             freq[prefix[i]]++;
  36.         }
  37.        
  38.         // Добавляем счетчик
  39.         long long ans = 0;
  40.         for (int j = pos + 1; j <= N; ++j) {
  41.             ans += freq[prefix[j]];
  42.         }
  43.        
  44.         cout << ans << "\n";
  45.     }
  46. };
  47.  
  48. int main(){
  49.     MedianSubsegmentsOptimized solver;
  50.     solver.solve();
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement