Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define Dmax 300001
- using namespace std;
- ifstream fin("is.in");
- ofstream fout("is.out");
- struct entry /// Structure for storing the states of the sweeping line array
- {
- int x, y1, y2, sgn;
- } A[Dmax]; /// The sweeping line array
- inline int max(int a, int b) /// Utility function
- {
- return (a > b ? a : b);
- }
- int N, T[Dmax << 2];
- long long Res;
- inline int cmp(const void *i, const void *j) /// Comparator function
- {
- entry *ei = (entry *) i, *ej = (entry *) j;
- if (ei->x != ej->x)
- return ei->x - ej->x;
- return ej->sgn - ei->sgn;
- }
- inline int query(int n, int l, int r, int a, int b) /// Query function for the segment tree
- {
- int m, t = 0;
- if (a <= l && r <= b)
- return T[n];
- else
- {
- m = (l + r) / 2;
- if (a <= m)
- t += query(2 * n, l, m, a, b);
- if (b > m)
- t += query(2 * n + 1, m + 1, r, a, b);
- }
- return t;
- }
- inline void update(int n, int l, int r, int p, int v) /// Update function for the segment tree
- {
- int m = (l + r) / 2;
- T[n] += v;
- if (l == r) return;
- if (p <= m)
- update(2 * n, l, m, p, v);
- else
- update(2 * n + 1, m + 1, r, p, v);
- }
- int main() /// Driver function
- {
- int i, n, x1, y1, x2, y2, MaxC = INT_MIN;
- fin >> N;
- for (n = i = 0; i < N; i++) /// Read the input file
- {
- fin >> x1 >> y1 >> x2 >> y2;
- if (y1 == y2) /// The given segment is horizontal
- A[n].x = x1, A[n].sgn = +1,
- A[n++].y1 = y1,
- A[n].x = x2, A[n].sgn = -1,
- A[n++].y1 = y1;
- else if (x1 == x2) /// The given segment is vertical
- A[n].x = x1, A[n].sgn = 0,
- A[n].y1 = y1, A[n++].y2 = y2;
- int crt = max(y1, y2);
- MaxC = max(MaxC, crt);
- }
- fin.close();
- qsort(A, n, sizeof(entry), cmp); /// Sort the sweeping line array
- for (i = 0; i < n; i++) /// Iterate through all the states of the sweeping line array
- if (A[i].sgn == 0) /// If the current state is a sweeping line ,i.e. a vertical segment then
- Res += query(1, 0, MaxC, A[i].y1, A[i].y2); /// Start a query for the interval [y1, y2] to check how many segments cross the sweeping line
- else /// Else if the current state is a horizontal segment then
- update(1, 0, MaxC, A[i].y1, A[i].sgn); /// Update its current state through the entire segment tree ,i.e. push it or pop it from the tree
- fout << Res; /// Return the output result
- fout.close();
- return 0;
- }
Add Comment
Please, Sign In to add comment