fork download
  1. /*
  2. PROBLEM: Count Valid Subarrays Without Forbidden Pairs Inside
  3.  
  4. Given:
  5. - N positions (1 to N)
  6. - M pairs (u, v)
  7.  
  8. Task: Count how many subarrays [l, r] don't contain any pair FULLY INSIDE.
  9.  
  10. A pair (u, v) is "fully inside" a subarray [l, r] if:
  11. - BOTH u and v are in the range [l, r]
  12. - Example: pair (2, 4) is fully inside [1, 5] because both 2 and 4 are in [1, 5]
  13.  
  14. A subarray is VALID if no pair is fully contained inside it. This means:
  15. - For every pair (a, b), at least one endpoint must be outside [l, r]
  16.  
  17. Example:
  18. N=5, M=2
  19. Pairs: (1, 3) and (2, 5)
  20.  
  21. Invalid subarrays: [1,3], [1,4], [1,5], [2,5] (pair fully inside)
  22. Valid subarrays: [1,1], [2,2], [3,3], [4,4], [5,5], [1,2], [2,3], [3,4], [4,5], [2,4], [3,5]
  23.  
  24. Key Insight:
  25. For a subarray [l, r] to be valid:
  26. - For every pair (a, b) where b <= r, we must have a < l (left endpoint outside)
  27. - In other words: l must be > the maximum left endpoint of all pairs ending at or before r
  28.  
  29. Approach:
  30. 1. For each right endpoint r, track the maximum left endpoint among all pairs ending at r
  31. 2. As we extend r, maintain the leftmost valid starting position (bound)
  32. 3. Count valid subarrays ending at r: all positions from bound+1 to r can be left endpoints
  33.  
  34. Time: O(N + M)
  35. */
  36.  
  37. #include <bits/stdc++.h>
  38. using namespace std;
  39.  
  40. int main() {
  41. ios::sync_with_stdio(false);
  42. cin.tie(nullptr);
  43.  
  44. int n, m;
  45. cin >> n >> m;
  46.  
  47. // max[r] = maximum left endpoint among all pairs with right endpoint r
  48. vector<int> mx(n + 1, 0);
  49.  
  50. for (int i = 0; i < m; i++) {
  51. int u, v;
  52. cin >> u >> v;
  53.  
  54. // Make sure l <= r
  55. int l = min(u, v);
  56. int r = max(u, v);
  57.  
  58. // Track the furthest left endpoint for each right endpoint
  59. mx[r] = max(mx[r], l);
  60. }
  61.  
  62. long long ans = 0;
  63.  
  64. // bound = leftmost position where pair would be fully inside
  65. int bound = 0;
  66.  
  67. // Try each position as the right endpoint
  68. for (int r = 1; r <= n; r++) {
  69. // Update bound: if any pair ends at r with left >= bound, update it
  70. bound = max(bound, mx[r]);
  71.  
  72. // Count subarrays ending at r
  73. // We can start from any position > bound up to r
  74. // That's (r - bound) choices
  75. ans += (long long)(r - bound);
  76. }
  77.  
  78. cout << ans << "\n";
  79.  
  80. return 0;
  81. }
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
536788995