POJ 3067.Japan【树状数组】【5月11】

Japan
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 25023   Accepted: 6738

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
求所有线的交点

思路:

按左右两侧从小到大排序,加入当前直线产生的交点数=已处理的直线中比当前右端点大的直线条数

树状数组维护

因为不知道K的范围,所以要开的大一点


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX = 1005;
struct ss
{
    int x, y;
}line[MAX*MAX];
bool cmp(ss a, ss b)
{
    if(a.x < b.x) return true;
    else if(a.x == b.x && a.y < b.y) return true;
    else return false;
}
int T, N, M, K, kase = 1;
long long ans, tree[MAX];
void add(int pos)
{
    while(pos <= M)
    {
        tree[pos] ++;
        pos += pos&(-pos);
    }
}
long long query(int pos)
{
    long long sum = 0;
    while(pos > 0)
    {
        sum += tree[pos];
        pos -= pos&(-pos);
    }
    return sum;
}
int main()
{
    scanf("%d", &T);
    while(T--)
    {
        ans = 0;
        memset(tree, 0, sizeof(tree));
        scanf("%d %d %d", &N, &M, &K);
        for(int i = 0;i < K; ++i)
        {
            scanf("%d %d", &line[i].x, &line[i].y);
        }
        sort(line, line+K, cmp);
        for(int i = 0;i < K; ++i)
        {
            add(line[i].y);
            ans += query(M)-query(line[i].y);//比当前节点右端点大的端点数
        }
        printf("Test case %d: %lld\n", kase++, ans);
    }
    return 0;
}


你可能感兴趣的:(C++,ACM,poj,树状数组)