首页 > 代码库 > POJ3067(JAPAN)

POJ3067(JAPAN)

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)

Sample Input

13 4 41 42 33 23 1

Sample Output

Test case 1: 5

这个题如果仔细分析一下,可以看出是求逆序对的问题,这个问题可以用树状数组解决。
树状数组中 , 因为这个题目已经是离散化(岛屿编号是1、2、3....)所以,可以直接算出逆序对
而在树状数组中求逆序对 就要用到这个东西:
for(i=1;i<=n;i++)
{
updata(b[i],1);
ans+=sum(n)-sum(b[i]);
}
这是个高效的代码。
#include <stdio.h>#include <string.h>#include <math.h>#include <algorithm>using namespace std;int b[2000],n,m,k;struct Node {    int a,b;}c[1000005];bool cmp(Node a,Node b){    if(a.a==b.a)return a.b<b.b;    return a.a<b.a;}int lowbit(int t){    return t&(-t);//管辖域 }int sum(int k) //求和 {    int sum=0;    while(k>0)    {        sum+=b[k];        k-=lowbit(k);    }   return sum;}void addorsub(int l,int d)//更新 {    while(l<=m)    {        b[l]+=d;        l+=lowbit(l);    }}int main(){    int T;    int temp=1;    int i,j,t,d;    __int64 s;    scanf("%d",&T);    while(T--)    { memset(b,0,sizeof(b));       scanf("%d %d %d",&n,&m,&k);          for(i=1;i<=k;i++)      {          scanf("%d %d",&c[i].a,&c[i].b);      }      sort(c+1,c+1+k,cmp);//排序       s=0;      for(i=1;i<=k;i++)//求逆序对       {          s+=sum(m)-sum(c[i].b);          addorsub(c[i].b,1);      }            printf("Test case %d: %I64d\n",temp,s);      temp++;    }    return 0; } 

 

POJ3067(JAPAN)