Japan(树状数组)

Japan
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 19724   Accepted: 5340

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

 

       题意:

       给出 T, 代表有 T 个 case。后每个 case 给出 N,M,K 三个数,代表东边有 N 个城市,代表西边有 M 个城市,后给出 K 条路,代表东边的城市 a 连 西边的城市 b。求出一共有多少个相交点。

 

       思路:

       树状数组。求逆序数,对 x 由小到大排序,若 x 相同,则对 y 由小到大排序。对于每个 j ,求出 sum(no [ i ].y )的个数,就是 i < j ,a[ i ] <= a[ j ] 的个数。所以 j - sum ( no [ i ]. y ) 代表逆序数的个数。要用long long,不然会WA。

 

        AC:

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

using namespace std;

typedef long long ll;
typedef struct { ll x, y; } node;

node no[1005 * 1005];
int n, m, k;
ll bit[1005];

bool cmp(node a, node b) {
        if (a.x != b.x) return a.x < b.x;
        return a.y < b.y;
}

void add(ll i, ll x) {
        while (i <= m) {
                bit[i] += x;
                i += i & -i;
        }
}

ll sum(ll i) {
        ll s = 0;
        while (i > 0) {
                s += bit[i];
                i -= i & -i;
        }
        return s;
}

int main() {
        int t;
        scanf("%d", &t);

        for (int tt = 1; tt <= t; ++tt) {
                memset(bit, 0, sizeof(bit));

                scanf("%d%d%d", &n, &m, &k);
                for (int i = 0; i < k; ++i) {
                        scanf("%d%d", &no[i].x, &no[i].y);
                }

                sort(no, no + k, cmp);

                ll ans = 0;
                for (ll i = 0; i < k; ++i) {
                        ans += (i - sum(no[i].y));
                        add(no[i].y, 1);
                }

                printf("Test case %d: %lld\n", tt, ans);
        }

        return 0;
}

 

 

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