灯塔(LightHouse)
Description
As shown in the following figure, If another lighthouse is in gray area, they can beacon each other.
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: N
2nd ~ (N + 1)th line: each line is X Y, means a lighthouse is on the point (X, Y).
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 )
Example
Input
3
2 2
4 3
5 1
Output
1
Restrictions
For 90% test cases: 1 <= n <= 3 * 105
For 95% test cases: 1 <= n <= 106
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.
视频里有讲解我尽然没看到,醉了。
就是求一下逆序对就行。
1 #include <cstdlib> 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6 #define LL long long 7 const int max_size = 4 * 1e6; 8 LL y_val[max_size]; 9 LL tmp_arry[max_size]; 10 ///加速代码,why 百度 11 const int SZ = 1<<20; 12 struct fastio{ 13 char inbuf[SZ]; 14 char outbuf[SZ]; 15 fastio(){ 16 setvbuf(stdin,inbuf,_IOFBF,SZ); 17 setvbuf(stdout,outbuf,_IOFBF,SZ); 18 } 19 }io; 20 struct Point 21 { 22 LL x, y; 23 } p[max_size]; 24 25 int cmp(const void *a, const void *b) 26 { 27 struct Point *c = (Point *)a; 28 struct Point *d = (Point *)b; 29 if(c->x != d->x) 30 return c->x - d->x; 31 else 32 return d->y - c->y; 33 } 34 35 LL Merge(LL *arr, LL beg, LL mid, LL end, LL *tmp_arr) 36 { 37 memcpy(tmp_arr+beg, arr+beg, sizeof(LL)*(end - beg + 1)); 38 LL i = beg; 39 LL j = mid+1; 40 LL k = beg; 41 LL inversion = 0; 42 while(i <= mid && j <= end) 43 { 44 if(tmp_arr[i] <= tmp_arr[j]) 45 arr[k++] = tmp_arr[i++]; 46 else 47 { 48 arr[k++] = tmp_arr[j++]; 49 inversion += mid - i + 1; 50 } 51 } 52 53 while(i <= mid) 54 arr[k++] = tmp_arr[i++]; 55 while(j <= end) 56 arr[k++] = tmp_arr[j++]; 57 return inversion; 58 } 59 60 LL MergeInversion(LL *arr, LL beg, LL end, LL *tmp_arr) 61 { 62 LL inversions = 0; 63 if(beg < end) 64 { 65 LL mid = (beg + end) >> 1; 66 inversions += MergeInversion(arr, beg, mid, tmp_arr); 67 inversions += MergeInversion(arr, mid+1, end, tmp_arr); 68 inversions += Merge(arr, beg, mid, end, tmp_arr); 69 } 70 return inversions; 71 } 72 73 int main() 74 { 75 LL n; 76 cin >> n; 77 for(int i = 0; i < n; i++) 78 { 79 cin >> p[i].x >> p[i].y; 80 } 81 82 qsort(p, n, sizeof(p[0]), cmp); 83 for(int i = 0; i < n; i++) 84 { 85 y_val[i] = p[i].y; 86 } 87 88 memcpy(tmp_arry, y_val, sizeof(LL)*n); 89 cout << n*(n-1) /2 - MergeInversion(y_val, 0, n-1, tmp_arry) << endl; 90 return 0; 91 }
然后再对代码进行优化吧,我的这段过不了最后一个点。因为多做了排序操作,没必要。