Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Segment Intersections: Manhattan Geometry

For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.

Input

In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:

$x_1 \; y_1 \; x_2 \; y_2$

The coordinates are given in integers.

Output

Print the number of intersections in a line.

Constraints

$1 \leq n \leq 100,000$

$ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$

Two parallel segments never overlap or touch.

The number of intersections $\leq 1,000,000$

Sample Input 1

6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7

Sample Output 1

3

Solution in C++ (judge verdict: Accepted)

#include<iostream>
using namespace std;
#include<cstdio>
#include<algorithm>
#include<set>
#include<iterator>

struct evp
{
	int y, x_l, x_r;
	int kind;
	bool operator < (const evp &E) const
	{
		if(y != E.y) return y < E.y;
		return kind < E.kind;
	}
};

evp init(int co_y, int co_x_l, int co_x_r, int kd)
{
	evp E;
	E.y = co_y, E.x_l = co_x_l, E.x_r = co_x_r, E.kind = kd;
	return E;
}

int main()
{
	int i, n;
	int x1, y1, x2, y2;
	scanf("%d", &n);
	evp *MG;
	MG = new evp [2 * n];
	int ev_n = 0;

	for(i = 0; i < n; i++){
		scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
		if(y1 != y2){
			if(y1 > y2) swap(y1, y2);
			MG[ev_n] = init(y1, x1, -1, 0);
			MG[ev_n + 1] = init(y2, x2, -1, 2);
			ev_n += 2;
		}else{
			if(x1 > x2) swap(x1, x2);
			MG[ev_n] = init(y1, x1, x2, 1);
			ev_n++;
		}
	}
	sort(MG, MG + ev_n);

	set<int> A;
	int count = 0;

	for(i = 0; i < ev_n; i++){
		switch(MG[i].kind){
			case 0:
				A.insert(MG[i].x_l);
				break;
			case 2:
				A.erase(MG[i].x_l);
				break;
			case 1:
				count += distance(A.lower_bound(MG[i].x_l), A.upper_bound(MG[i].x_r));
				break;
		}
	}
	printf("%d\n", count);
	return 0;
}