POJ-3067 Japan---Deformation of tree-like arrays in reverse order

Topic link:

https://vjudge.net/problem/POJ-3067

Topic meaning:

There are N and M cities on the east coast and west coast of the island of Japan respectively. Now highways are built to connect the cities on the east and west coasts. Find the number of intersections.

Problem solving ideas:

Write down each telling highway as (x, y), that is, build a road between the xth city on the east bank and the yth city on the west bank. When the two paths have an intersection, (x1-x2)*(y1-y2) < 0. Therefore, each road is sorted by x from small to large. If x is the same, it is sorted by y from small to large. Then use the tree array to update online according to the sorted roads, and find the sum of the inverse numbers of y to be the number of intersections.

such as example

1 4
2 3
3 2
3 1

After sorting

1 4
2 3
3 1
3 2

1. Add 1 4, at this time the element larger than 4 is 0, and the number of intersection points is 0

2. Add 2 3, the number of elements larger than 3 is 1, and the number of intersection points is 1

3. Add 3 1. At this time, there are two numbers larger than 1, and the number of intersection points is 3

4. Add 3 2. At this time, there are 2 numbers larger than 2, and the number of intersection points is 5.

If you add 3 2 first, and then add 3 1, it will lead to 3 1 when calculating the intersection point, 3 2 is included, but there is no intersection, so the sorting order is in the same x and y from small to large.

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<string>
 5 #include<map>
 6 #include<set>
 7 #include<cmath>
 8 #include<algorithm>
 9 using namespace std;
10 typedef long long ll;
11 const int maxn = 1000000 + 10;
12 int n, m, T, k, cases;
13 struct node
14 {
15     int x, y;
16     bool operator <(const node& a)const
17     {
18         return x < a.x || x == a.x && y < a.y;
19     }
20 };
21 node a[maxn];
22 int tree[10000];
23 int lowbit(int x)
24 {
25     return x & (-x);
26 }
27 ll sum(int x)
28 {
29     ll ans = 0;
30     while(x)
31     {
32         ans += tree[x];
33         x -= lowbit(x);
34     }
35     return ans;
36 }
37 void add(int x, int d)
38 {
39     while(x <= m)
40     {
41         tree[x] += d;
42         x += lowbit(x);
43     }
44 }
45 int main()
46 {
47     cin >> T;
48     while(T--)
49     {
50         cin >> n >> m >> k;
51         memset(tree, 0, sizeof(tree));
52         for(int i = 1; i <= k; i++)
53         {
54             scanf("%d%d", &a[i].x, &a[i].y);
55         }
56         sort(a + 1, a + 1 + k);
57         ll ans = 0;
58         for(ll i = 1; i <= k; i++)
59         {
60             add(a[i].y, 1);
61             ans += (i - sum(a[i].y));
62         }
63         printf("Test case %d: %lld\n", ++cases, ans);
64     }
65     return 0;
66 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324851151&siteId=291194637