Japan
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 23641 | Accepted: 6384 |
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 file 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 first 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)
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
告诉你k对城市连通,问你多少个城市相交,相交的条件是:(Ax - Bx) * (Ay - By) < 0。
排序按x从小到大,相等则按y从小到大。
AC代码:
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int MAXN = 2005;
typedef long long ll;
struct node
{
/* data */
int x, y;
}a[MAXN * MAXN];
int n, m, k, c[MAXN];
bool cmp(node a, node b)
{
if(a.x == b.x) return a.y < b.y;
return a.x < b.x;
}
int lowbit(int x)
{
return x & (-x);
}
void update(int x)
{
for(int i = x; i <= m; i += lowbit(i))
c[i]++;
}
ll get_sum(int x)
{
ll sum = 0;
for(int i = x; i > 0; i -= lowbit(i))
sum += c[i];
return sum;
}
int main(int argc, char const *argv[])
{
int t;
scanf("%d", &t);
for(int cas = 1; cas <= t; ++cas) {
memset(c, 0, sizeof(c));
scanf("%d%d%d", &n, &m, &k);
for(int i = 1; i <= k; ++i)
scanf("%d%d", &a[i].x, &a[i].y);
sort(a + 1, a + 1 + k, cmp);
ll ans = 0;
for(int i = 1; i <= k; ++i) {
update(a[i].y);
ans += i - get_sum(a[i].y);
}
printf("Test case %d: %lld\n", cas, ans);
}
return 0;
}