fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <unordered_map>
  4. using namespace std;
  5.  
  6. int main() {
  7. int n, x, y;
  8. cin >> n >> x >> y;
  9. vector<int> b(n + 1);
  10.  
  11. // Input array
  12. for (int i = 1; i <= n; i++) {
  13. cin >> b[i];
  14. }
  15.  
  16. unordered_map<int, int> countMap; // To store frequency of counts
  17. countMap[0] = 1; // Initialize with count 0
  18. int c = 0; // Count of valid subarrays
  19. int result = 0; // Total valid subarrays count
  20.  
  21. // Iterate through the array
  22. for (int i = 1; i <= n; i++) {
  23. // Increment or decrement the count based on the value in the array
  24. if (b[i] == x) {
  25. c++;
  26. } else if (b[i] == y) {
  27. c--;
  28. }
  29.  
  30. // If this count has been seen before, it means there are some subarrays
  31. // that have equal number of x and y
  32. result += countMap[c];
  33.  
  34. // Increment the count of this difference
  35. countMap[c]++;
  36. }
  37.  
  38. cout << result << endl; // Print the result
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0s 5320KB
stdin
6
1 1 2 2 1 1
stdout
6