Japan 逆序数

来源:互联网 发布:笛卡尔积 sql 编辑:程序博客网 时间:2024/06/17 20:21
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

13 4 41 42 33 23 1

Sample Output

Test case 1: 5


题意很明确,就是求所有线的交点总数,是两两相交点

做法挺有意思,一开始我只获得了两个关键字:排序。我摸索了一番,发现对x排序,然后对y求逆序数,即为所求(可以在纸上画画)

#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>#define lowbit(x) (x & (-x))using namespace std;const int N = 1e6 + 5;struct node{    int x, y;}a[N];int c[N];void Update(int k){    for(int i = k; i <= 1000; i += lowbit(i))        c[i]++;}int GetSum(int k){    int sum = 0;    for(int i = k; i > 0; i -= lowbit(i))        sum += c[i];    return sum;}bool cmp(node m, node n){    if(m.x != n.x)        return m.x < n.x;    return m.y < n.y;}int main(){    int t, n, m, k;    scanf("%d", &t);    for(int j = 1; j <= t; j++)    {        memset(c, 0, sizeof(c));        scanf("%d%d%d", &n, &m, &k);        for(int i = 0; i < k; i++)            scanf("%d%d", &a[i].x, &a[i].y);        sort(a, a + k, cmp);        long long ans = 0;        for(int i = 0; i < k; i++)        {            Update(a[i].y);            ans += i + 1 - GetSum(a[i].y);        }        printf("Test case %d: %lld\n", j, ans);    }    return 0;}


原创粉丝点击