Home BOJ. Northwesterly Wind (5419)
Post
Cancel

BOJ. Northwesterly Wind (5419)

[Link] https://www.acmicpc.net/problem/5419


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static StringBuilder sb = new StringBuilder();
	static int[] seg;
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		sb = new StringBuilder();
		int[] arr;
		int test = toi(br.readLine());
		while(test-- > 0) {
			int n = toi(br.readLine());
			ArrayList<Point> points = new ArrayList<>();

			for(int i = 0; i < n; i++) {
				arr = getArr();
				points.add(new Point(arr[0], arr[1]));
			}

			Collections.sort(points, (l, r) -> Integer.compare(l.y, r.y));
			int rankIdx = 0, cmp = points.get(0).y;

			for(Point p : points) {
				if(p.y != cmp) p.rank = ++rankIdx;
				else p.rank = rankIdx;
				cmp = p.y;
			}

			Collections.sort(points, (l, r) -> {
				if(l.x == r.x) return l.y < r.y ? 1 : -1;
				return l.x > r.x ? 1 : -1;
			});

			seg = new int[1 << (int)Math.ceil(Math.log(rankIdx + 1) / Math.log(2)) + 1];

			long cnt = 0;
			for(Point p : points) {
				cnt += get(0, rankIdx, 1, p.rank);
				update(0, rankIdx, 1, p.rank);
			}
			sb.append(cnt).append("\n");
		}
		print(sb);
	}

	static void update(int left, int right, int idx, int h) {
		if(right < h || h < left) return;
		seg[idx]++;
		if(left == right) return;
		int mid = (left + right) >> 1;
		if(mid + 1 <= h) update(mid + 1, right, 2 * idx + 1, h);
		else update(left, mid, 2 * idx, h);
	}

	static int get(int left, int right, int idx, int h) {
		if(left >= h) return seg[idx];
		if(right < h) return 0;
		int mid = (right + left) >> 1;
		return get(left, mid, 2 * idx, h) + get(mid + 1, right, 2 * idx + 1, h);
	}

	static class Point {
		int x, y, rank;
		Point(int x, int y) { this.x = x; this.y = y; }
	}

	static int toi(String s) { return Integer.parseInt(s); }
	static long tol(String s) { return Long.parseLong(s); }
	static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static int[] getArr() throws IOException { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.