Japan POJ - 3067(逆序对)

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 <= 500000, N <= 500000). 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条连线。问连线有多少交点。
思路:
回顾一下经典的逆序对问题。假设位置为vi, 权值为wi。
那么构成一对逆序对的条件是vi < vj ,且wi > wj。
同样拓展到本题,左边位置为xi,右边位置为yi。
那么出现交点的条件是,xi < xj, 且yi > yj。

这就等价于经典逆序对问题了。可以看到,逆序对问题都是每个点对应两个权值,然后出现相反的大小关系。那么解题的关键就在于先将其中一个权值排序(或者重新映射,使得其中一个权值递增),然后用树状数组维护另一个权值

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long ll;
const int maxn = 5e5 + 7;

ll c[maxn + 5];

struct Node
{
    int x,y;
    bool operator < (const Node &b)const
    {
        if(y == b.y)return x < b.x;
        return y < b.y;
    }
}nodes[maxn + 5];

void add(int x,int v)
{
    while(x <= maxn)
    {
        c[x] += v;
        x += x & (-x);
    }
}

ll query(int x)
{
    ll res = 0;
    while(x)
    {
        res += c[x];
        x -= x & (-x);
    }
    return res;
}

int main()
{
    int T;scanf("%d",&T);
    int kase = 0;
    while(T--)
    {
        memset(c,0,sizeof(c));
        int n,m,k;scanf("%d%d%d",&n,&m,&k);
        for(int i = 1;i <= k;i++)
        {
            scanf("%d%d",&nodes[i].x,&nodes[i].y);
        }
        sort(nodes + 1,nodes + 1 + k);
        ll ans = 0;
        for(int i = 1;i <= k;i++)
        {
            ans += query(maxn) - query(nodes[i].x);
            add(nodes[i].x,1);
        }
        printf("Test case %d: ",++kase);
        printf("%lld\n",ans);
    }
    return 0;
}



发布了628 篇原创文章 · 获赞 17 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/tomjobs/article/details/104081957