Japan
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 25023 | Accepted: 6738 |
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的範圍,所以要開的大一點
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX = 1005;
struct ss
{
int x, y;
}line[MAX*MAX];
bool cmp(ss a, ss b)
{
if(a.x < b.x) return true;
else if(a.x == b.x && a.y < b.y) return true;
else return false;
}
int T, N, M, K, kase = 1;
long long ans, tree[MAX];
void add(int pos)
{
while(pos <= M)
{
tree[pos] ++;
pos += pos&(-pos);
}
}
long long query(int pos)
{
long long sum = 0;
while(pos > 0)
{
sum += tree[pos];
pos -= pos&(-pos);
}
return sum;
}
int main()
{
scanf("%d", &T);
while(T--)
{
ans = 0;
memset(tree, 0, sizeof(tree));
scanf("%d %d %d", &N, &M, &K);
for(int i = 0;i < K; ++i)
{
scanf("%d %d", &line[i].x, &line[i].y);
}
sort(line, line+K, cmp);
for(int i = 0;i < K; ++i)
{
add(line[i].y);
ans += query(M)-query(line[i].y);//比當前節點右端點大的端點數
}
printf("Test case %d: %lld\n", kase++, ans);
}
return 0;
}