题目描述
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.
输入格式
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.
输出格式
For each test case write one line on the standard output:
Test case (case number): (number of crossings)
样例数据
样例输入
1
3 4 4
1 4
2 3
3 2
3 1
样例输出
Test case 1: 5
题目分析
因为题目说了最多两条线有一个交点,故三条线不共交点,可以转化为逆序对做。
分析什么情况会有交点。
只有当a.x
源代码
#include<algorithm>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<cstdlib>
#include<vector>
#include<cstdio>
#include<cmath>
#include<queue>
#include<map>
using namespace std;
inline const int Get_Int() {
int num=0,bj=1;
char x=getchar();
while(x<'0'||x>'9') {
if(x=='-')bj=-1;
x=getchar();
}
while(x>='0'&&x<='9') {
num=num*10+x-'0';
x=getchar();
}
return num*bj;
}
const int maxn=500005;
struct BIT { //树状数组
long long n,c[maxn];
inline int Lowbit(int x) { //低位操作
return x&(-x);
}
void init(int n) {
this->n=n;
memset(c,0,sizeof(c));
}
void add(int x,int v) {
for(int i=x; i<=n; i+=Lowbit(i))c[i]+=v;
}
long long sum(int x) { //求出1~s的区间和
long long s=0;
for(int i=x; i; i-=Lowbit(i))s+=c[i];
return s;
}
} bit;
map<long long,long long>M;
map<long long,long long>::iterator it;
long long n,a[500005],b[500005];
void Discretization() { //a是待离散数组 b是离散后数组
M.clear();
memset(b,0,sizeof(b));
for(int i=1; i<=n; i++)M[a[i]]=1;
int i=1;
for(it=M.begin(); it!=M.end(); it++,i++)it->second=i;
for(int i=1; i<=n; i++)b[i]=M[a[i]];
}
long long ans=0;
int main() {
while(true) {
n=Get_Int();
if(n==0)break;
ans=0;
bit.init(n);
for(int i=1; i<=n; i++)a[i]=Get_Int();
Discretization();
for(int i=n; i>=1; i--) {
bit.add(b[i],1);
ans+=bit.sum(b[i]-1);
}
printf("%lld\n",ans);
}
return 0;
}