欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

POJ 3067 Japan【树状数组+逆序对】

程序员文章站 2022-05-10 19:58:08
...


传送门:POJ 3067


Japan
Time Limit: 1000MS Memory Limit: 65536K

Problem 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
1
3 4 4
1 4
2 3
3 2
3 1

Sample Output
Test case 1: 5



题意:
日本岛东海岸与西海岸分别有N和M个城市,现在修高速公路连接东西海岸的城市,求交点个数。


题解:

第i条边的端点分别为xi,yi。
将k条边按x由小到大排序,如果x相等,则按y有小到大排序。然后计算y的逆序数,y的逆序数即为答案。

原因:
排完序后,我们先考虑前k条边,假设第k条边建完了,因为是按x有小到大排的,所有前k-1条的x一定小于第k条,那么只要的前k-1条的y大于第k条的y,就会形成交点,即前k-1条边y在[yk,m]内的点的个数,所以交点数即为逆序数。
所以就将问题转化为区间求和的问题,用树状数组解决。

题目k的范围很迷,我一开始范围定的105小了,一直错,换成106 才过,还有就是要用long long才行。



AC代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int N=1100000;
int n,m,k,t;
int c[N];
struct Node
{
  int x,y;
}roads[N];
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,int p)
{
  while(x<=m)
  {
    c[x]+=p;
    x+=lowbit(x);
  }
}
ll getsum(int x)
{
  ll ans=0;
  for(int i=x;i>0;i-=lowbit(i))
  {
    ans+=c[i];
  }
  return ans;
}
int main()
{
  int ca=0;
  scanf("%d",&t);
  while(t--)
  {
    memset(c,0,sizeof(c));
    scanf("%d%d%d",&n,&m,&k);
    for(int i=1;i<=k;i++)
    {
      scanf("%d%d",&roads[i].x,&roads[i].y);
    }
    sort(roads+1,roads+1+k,cmp);
    ll ans=0;
    for(int i=1;i<=k;i++)
    {
      update(roads[i].y,1);
      ans+=(i-getsum(roads[i].y));
    }
    printf("Test case %d: %I64d\n",++ca,ans);
  }
  return 0;
}

相关标签: 逆序对