Advertisement
tepyotin2

Intersection Points

Jul 3rd, 2025
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include <algorithm>
  2. #include <bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6. const int N = 100000;
  7.  
  8. struct Event {
  9.     int x;
  10.     int y1, y2; // vertical line
  11.     int type; // 0, 1, 2
  12.  
  13.     Event() { }
  14.     Event(int x, int y1, int y2, int type): x(x), y1(y1), y2(y2), type(type) { }
  15. };
  16.  
  17. int fw[N + 1];
  18. vector<Event> events;
  19. vector<int> coord;
  20.  
  21. void update(int index, int value) {
  22.     for (; index <= N; index += index&-index) {
  23.         fw[index] += value;
  24.     }
  25. }
  26.  
  27. int query(int index) {
  28.     int ans = 0;
  29.     for (; index > 0; index -= index&-index) {
  30.         ans += fw[index];
  31.     }
  32.     return ans;
  33. }
  34.  
  35. bool comp(Event a, Event b) {
  36.     if (a.x == b.x) return a.type < b.type;
  37.     return a.x < b.x;
  38. }
  39.  
  40. int main() {
  41.     ios_base::sync_with_stdio(0), cin.tie(0);
  42.  
  43.     int n;
  44.     cin >> n;
  45.  
  46.     for (int i = 1; i <= n; i++) {
  47.         int x1, y1, x2, y2;
  48.         cin >> x1 >> y1 >> x2 >> y2;
  49.  
  50.         x1 += 1e6, y1 += 1e6, x2 += 1e6, y2 += 1e6;
  51.  
  52.         if (x1 == x2) {
  53.             // vertical line
  54.             events.push_back(Event(x1, y1, y2, 1));
  55.         } else {
  56.             // horizontal line
  57.             events.push_back(Event(x1, y1, y2, 0));
  58.             events.push_back(Event(x2, y1, y2, 2));
  59.         }
  60.  
  61.         coord.push_back(y1);
  62.         coord.push_back(y2);
  63.     }
  64.  
  65.     sort(coord.begin(), coord.end());
  66.     coord.resize(unique(coord.begin(), coord.end()) - coord.begin());
  67.  
  68.     sort(events.begin(), events.end(), comp);
  69.  
  70.     long long ans = 0;
  71.     for (Event e: events) {
  72.         if (e.type == 1) {
  73.             ans += query(e.y2) - query(e.y1 - 1);
  74.         } else if (e.type == 0) {
  75.             update(e.y1, 1);
  76.         } else if (e.type == 2) {
  77.             update(e.y2, -1);
  78.         }
  79.     }
  80.     cout << ans << '\n';
  81.  
  82.     return 0;
  83. }
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement