Description
Japan plans to welcome the acmicpc world finals and a lot of roads must be built for the venue. japan is tallisland 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 arenumbered 1, 2 ,... from north to south. each superhighway is straight line andconnects city on the East Coast with city of the West Coast. the funding forthe construction is guaranteed by ACM. A major portion of the sum is determinedby the number
Of crossings between superhighways. at most two superhighwayscross at one location. Write a program that calculates the number of thecrosings 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 connectedby the superhighway. the first one is the number of
City on the east coastand second one is the number of the City of the West Coast.
Output
For each test case write oneline 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
Introduction: There are n cities on the left, M cities on the right, and the cities are arranged vertically at a time. There are K highways that tell each road to connect two cities. Calculate the number of intersections on these highways.
Solution: First, you can sort the roads in ascending order on the left, and at the same time on the left, in ascending order on the right. The problem is converted to the reverse order of the city on the right of the road.
Method: Tree array.
The J-1 represents how many paths have been processed. Sum (x) indicates the number of numbers earlier than X. (J-1)-sum (x) is the number of numbers greater than X before X.
#include<cstdio>#include<algorithm>#include<cstring>#include<iostream>using namespace std;int C[1010], N, M, K;struct node{int a,b;}path[1000010];bool cmp(node x, node y){if(x.a==y.a){return x.b<y.b;}return x.a<y.a;};int lowbit(int x){ return x&(-x);};void update(int x, int val){ for(int i=x;i<=M;i+=lowbit(i)) { C[i] += val; }};int sum(int x){ int temp=0; for(int i=x;i>=1;i-=lowbit(i)) { temp += C[i]; } return temp;};int main(){int T;scanf("%d",&T);for(int i = 1;i<=T;i++){scanf("%d%d%d",&N,&M,&K);for(int j = 1;j<=K;j++){scanf("%d%d",&path[j].a,&path[j].b);}sort(path+1,path+1+K,cmp);memset(C,0,sizeof(C));long long ans = 0;for(int j = 1;j<=K;j++){ans += ((j - 1) - sum(path[j].b));update(path[j].b,1);}printf("Test case %d: %I64d\n",i,ans);}return 0;}