POJ-3067-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

1
3 4 4
1 4
2 3
3 2
3 1
Sample Output

Test case 1: 5

题意:东边有N个城市,南边有M个城市,在这些东南城市的中间有K条道路,每一条道路都连着一个东部城市和一个西部的城市,问这些连线有多少个交叉点。

第一眼看不会想到用树状数组来求逆序对,但是仔细观察一下,当左边的顺序固定时(从小到大),如果想存在交叉点,那么当前的点必须要比之前的点小。
比如;
第一个道路的连接的城市为1和4,下一个道路连接东边的城市编号为2,如果想有交叉点,那么另一个编号必须要小于4。
这样就转换成了 对南边的城市求逆序对个数的问题(前提是东边城市编号从小到大排序,如果相等则对南边城市编号从小到大排序)

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define max(a,b)   (a>b?a:b)
#define min(a,b)   (a
#define swap(a,b)  (a=a+b,b=a-b,a=a-b)
#define memset(a)  memset(a,0,sizeof(a))
#define X (sqrt(5)+1)/2.0  //Wythoff
#define Pi acos(-1)
//#define e  2.718281828459045
using namespace std;
typedef long long int LL;
const int MAXL(1e6);
const int INF(0x3f3f3f3f);
const int mod(1e9+7);
int dir[4][2]= {{-1,0},{1,0},{0,1},{0,-1}};
LL c[MAXL+50];
int maxY;
struct node
{
    int x,y;
}s[MAXL+50];
bool cmp(struct node p,struct node q)
{
    if(p.x==q.x)
        return p.yreturn p.xint n,m,k;
int lowbit(int t)
{
    return t&(-t);
}
void Update(int i,int v)
{
    while(i<=m)
    {
        c[i]+=v;
        i+=lowbit(i);
    }
}
LL Getsum(int i)
{
    LL ans=0;
    while(i>0)
    {
        ans+=c[i];
        i-=lowbit(i);
    }
    return ans;
}
int main()
{
    int T;
    scanf("%d",&T);
    int CASE=1;
    while(T--)
    {
        memset(c);
        scanf("%d%d%d",&n,&m,&k);
        for(int i=1;i<=k;i++)
        {
            scanf("%d%d",&s[i].x,&s[i].y);
        }
        sort(s+1,s+k+1,cmp);
        LL ans=0;
        for(int i=1;i<=k;i++)
        {
            Update(s[i].y,1);
            ans+=i-Getsum(s[i].y);
        }
        cout<<"Test case "<": ";
        cout<return 0;
}

你可能感兴趣的:(线段树/树状数组)