Advertisement
asdfg0998

Untitled

May 4th, 2025
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1. // Linear Time Approach - O(n) time complexity
  2. long long countStableSubsegmentsLinear(const vector<long long>& capacity) {
  3.     int n = capacity.size();
  4.     long long count = 0;
  5.    
  6.     // Map to store endpoints with the same value
  7.     // For each value v, we store indices where capacity[i] = v
  8.     unordered_map<long long, vector<int>> valueToIndices;
  9.    
  10.     // Prefix sum for efficient sum calculation
  11.     vector<long long> prefixSum(n + 1, 0);
  12.     for (int i = 0; i < n; i++) {
  13.         prefixSum[i + 1] = prefixSum[i] + capacity[i];
  14.         valueToIndices[capacity[i]].push_back(i);
  15.     }
  16.    
  17.     // For each possible value that could be at endpoints
  18.     for (const auto& pair : valueToIndices) {
  19.         long long value = pair.first;
  20.         const vector<int>& indices = pair.second;
  21.        
  22.         // Check all pairs of indices where capacity[i] = value
  23.         for (int i = 0; i < indices.size(); i++) {
  24.             for (int j = i + 1; j < indices.size(); j++) {
  25.                 int l = indices[i];
  26.                 int r = indices[j];
  27.                
  28.                 // Skip if the segment length is less than 3
  29.                 if (r - l < 2) continue;
  30.                
  31.                 // Calculate sum between l+1 and r-1
  32.                 long long sumBetween = prefixSum[r] - prefixSum[l + 1];
  33.                
  34.                 // Check if the subsegment is stable
  35.                 if (value == sumBetween) {
  36.                     count++;
  37.                 }
  38.             }
  39.         }
  40.     }
  41.    
  42.     return count;
  43. }
  44.  
  45. int main() {
  46.  
  47.    
  48.     vector<long long> capacity = {9,3,1,2,3,9,10};
  49.    
  50.     long long result = countStableSubsegmentsLinear(capacity);
  51.     cout << result << endl;
  52.    
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement