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

树状数组:
先按x排序,然后再对y求前面比他大的数的个数
但有两个地方需要注意
1. 题目没直接给k的数据范围,数组要开到1000000
2. 用long long

#include <iostream> 
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm> 
#define N 1005
using namespace std;
int n, m;
long long ans[N];
struct road
{
    int east, west;
    friend bool operator < (road a, road b)
    {
        if (a.east == b.east)   return a.west < b.west;
        return a.east < b.east;
    }
}rr[N*N];
void update(int x, int val)
{
    while(x <= m)
    {
        ans[x] += val;
        x += x&-x;
    }
}
long long sum(int x)
{
    long long ret = 0;
    while (x > 0)
    {
        ret += ans[x];
        x -= x&-x;
    }
    return ret;
}
int main()
{
#ifndef ONLINE_JUDGE
// freopen("1.txt", "r", stdin);
#endif
    int i, j, K, T;
    long long ret;
    scanf("%d", &T);
    for (j = 1; j <= T; j++)
    {
        ret = 0;
        memset(ans, 0, sizeof(ans));
        scanf("%d%d%d", &n, &m, &K);
        for (i = 0; i < K; i++)
            scanf("%d%d", &rr[i].east, &rr[i].west);
        sort(rr, rr+K);
        for (i = 0; i < K; i++)
        {
            update(rr[i].west, 1);
            ret += sum(m)-sum(rr[i].west);
        }
        printf("Test case %d: %lld\n", j, ret);
    }
    return 0;
}

你可能感兴趣的:(poj-3067-Japan(树状数组))