Description
Japan plans to welcome the ACM ICPC World Finals and a lot of roads must be built for the venue. Japan is tall island with N cities on the East coast and M cities on the West coast (M 1000; N 1000). K superhighways will be build. Cities on each coast are numbered 1; 2; : : : from North to South. Each superhighway is straight line and connects city on the East coast with city of the West coast. The funding for the construction is guaranteed by ACM. A major portion of the sum is determined by the number of crossings between superhighways. At most two superhighways cross at one location. Write a program that calculates the number of the crossings between superhighways.
Input
The input le starts with T | the number of test cases. Each test case starts with three numbers | N, M, K. Each of the next K lines contains two numbers | the numbers of cities connected by the superhighway. The rst one is the number of the city on the East coast and second one is the number of the city of the West coast.
Output
For each test case write one line on the standard output:
Test case < case number >: < number of crossings >
Sample Input
1
3 4 4
1 4
2 3
3 2
3 1
Sample Output
Test case 1: 5
思路:
题意是求线段的总交点数,设东部的城市为an,西部为bn,则对于两条线段a1b1、a2b2,相交的条件是((a1 < a2)&&(b1>b2))||((a1>a2)&&(b1<b2)) 。
矩阵中,对于(a, b)与它相交的线段则处于左下方与右上方的两个子矩阵中(不包括边界)。
用树状数组可以解决。
Code:
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long LL; 4 const int maxn = 1000 + 5; 5 LL mat[maxn][maxn], n, m; 6 int a[maxn*maxn], b[maxn*maxn]; 7 8 int lowbit(int x) {return x & -x;} 9 10 void add(int x, int y, int d) { 11 for (int i = x; i <= n; i += lowbit(i)) 12 for (int j = y; j <= m; j += lowbit(j)) 13 mat[i][j] += d; 14 } 15 16 LL sum(int x, int y) { 17 if (x <= 0) return 0; 18 if (y <= 0) return 0; 19 LL ret = 0; 20 for (int i = x; i > 0; i -= lowbit(i)) 21 for (int j = y; j > 0; j -= lowbit(j)) 22 ret += mat[i][j]; 23 return ret; 24 } 25 26 int main() { 27 ios::sync_with_stdio(false); 28 int T, k, kase = 0; 29 cin >> T; 30 while(cin >> n >> m >> k) { 31 memset(mat, 0, sizeof(mat)); 32 for (int i = 0; i < k; ++i) { 33 cin >> a[i] >> b[i]; 34 add(a[i], b[i], 1); 35 } 36 LL ans = 0; 37 for (int i = 0; i < k; ++i) { 38 ans += sum(n, b[i]-1)+sum(a[i]-1, m)-sum(a[i], b[i]-1)-sum(a[i]-1, b[i]); 39 } 40 cout << "Test case " << ++kase << ": "; 41 cout << ans / 2 << endl; 42 } 43 44 return 0; 45 }