燈塔(LightHouse)

Description

As shown in the following figure, If another lighthouse is in gray area, they can beacon each other.ios

For example, in following figure, (B, R) is a pair of lighthouse which can beacon each other, while (B, G), (R, G) are NOT.數組

Input

1st line: Nspa

2nd ~ (N + 1)th line: each line is X Y, means a lighthouse is on the point (X, Y).3d

Output

How many pairs of lighthourses can beacon each other指針

( For every lighthouses, X coordinates won't be the same , Y coordinates won't be the same )code

Example

Inputblog

3
2 2
4 3
5 1

Output排序

1

Restrictions

For 90% test cases: 1 <= n <= 3 * 105ip

For 95% test cases: 1 <= n <= 106ci

For all test cases: 1 <= n <= 4 * 106

For every lighthouses, X coordinates won't be the same , Y coordinates won't be the same.

1 <= x, y <= 10^8

Time: 2 sec

Memory: 256 MB

Hints

The range of int is usually [-231, 231 - 1], it may be too small.

第一眼看到這題時第一反應是用樹狀數組,可是發現數據太大,開不了10的6次方的二維數組,看了別人的博客才知道是用歸併排序。

先理解一下題意,要求有多少對兩兩互相照亮的燈塔,怎麼樣才能是兩兩互相照亮的呢,兩點的斜率爲正,也就是按x遞增排序,y也遞增。

這樣我們就能夠把n個點對x進行排序,找到y有多少對是順序對就行,這就能夠用到歸併排序,在對左右兩個集合合併時,i,j分別爲左右兩個集合的

指針,若是le[i]<ri[j],正序對加上n2-j+1對,就這樣去考慮。還有就是那裏不能用<algorithm>,能夠用stdlib.h裏的qsort()。

 

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <cstdlib>
 5 
 6 using namespace std;
 7 
 8 
 9 
10 struct w
11 {
12        int x;
13        int y;
14 }k[5100000];
15 int yi[5100000];
16 long long ans;
17 int le[5000005],ri[5000005];
18 
19 int cmp( const void *a ,const void *b)
20 { 
21     return (*(w *)a).x > (*(w *)b).x ; 
22 }
23 
24 
25 void merge(int l,int mi,int r)
26 {
27      int i,j,p,n1=mi-l+1,n2=r-mi;
28      const int MAX=500000005;
29      
30      for (int i=1;i<=n1;i++)
31      le[i]=k[l+i-1].y;
32      for (int i=1;i<=n2;i++)
33      ri[i]=k[mi+i].y;
34       
35       le[n1+1]=MAX;ri[n2+1]=MAX;
36       i=1;j=1;
37       for (int p=l;p<=r;p++)
38       {
39           if (le[i]>ri[j])
40           k[p].y=ri[j++];
41           else
42           {
43               k[p].y=le[i++];
44               ans+=n2-j+1;
45           //    cout <<ans<<endl;
46           }
47       }
48 }
49 void mergesort(int l,int r)
50 {
51      if (l==r)
52      return;
53      int mid=l+(r-l)/2;
54      mergesort(l,mid);
55      mergesort(mid+1,r);
56      merge(l,mid,r);
57 }
58 
59 int main()
60 {
61     int n;
62     cin>>n;
63     for (int i=0;i<n;i++)
64     cin>>k[i].x>>k[i].y;
65     qsort(k,n,sizeof(k[0]),cmp);
66     ans=0;
67     mergesort(0,n-1);
68     cout <<ans<<endl;
69     return 0;
70 }
相關文章
相關標籤/搜索