Japan POJ - 3067(树状数组)

日本为了ACM ICPC世界总决赛准备建设超级高速公路,需要计算交叉点数量。每条超级高速公路连接东西海岸的城市,最多两两相交。题目要求根据输入的测试案例计算交叉点总数。通过排序和树状数组解决此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Japan

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

题意: 左右两边分别有n和m个城市,有k条边;然后k行给出连边,问共有多少交叉点;
思路: 交叉点产生的条件:用图解释:
当一条边的左端点高于另一条边的左端点,并且其右端点低于另一条边的右端点
在这里插入图片描述
我们将每条边的按左端点从小到大排序,左端点相同按右端点从小到大排序;
处理完后将题中例子画出来:
在这里插入图片描述
在这里插入图片描述
左边从上到下遍历时,当其右端点存在之前连得边的右端点比该边的右端点小,可以遍历左端点时将其右端点标记加一,同时查找此边的右端点之前有几个比他小的即可;用树状数组维护;
代码

//#include<bits/stdc++.h>
#include<cstdio>
#include<string.h>
#include<algorithm>
#define ll long long
using namespace std;
const int maxn=1e6+7;
ll a[maxn];ll n,m;
struct node
{
    ll x,y;
}stu[maxn];
bool cmp(node a,node b)
{
    if(a.x==b.x)
        return a.y<b.y;
    return a.x<b.x;
}
ll lowbit(ll x)
{
    return x&(-x);
}
void change(ll i)
{
    while(i<=maxn)
    {
        a[i]++;
        i+=lowbit(i);
    }
}
ll getsum(ll i)
{
    ll ans=0;
    while(i>0)
    {
        ans+=a[i];
        i-=lowbit(i);
    }
    return ans;
}
int main()
{
    ll t;
    scanf("%lld",&t);
    ll cnt=0;
    while(t--)
    {
        memset(a,0,sizeof(a));
        ll k;
        scanf("%lld%lld%lld",&n,&m,&k);
        for(int i=1;i<=k;i++)
            scanf("%lld%lld",&stu[i].x,&stu[i].y);
        sort(stu+1,stu+1+k,cmp);
        ll ans=0;
        for(int i=1;i<=k;i++)
        {
            //printf("%lld %lld\n",stu[i].x,stu[i].y);
            ans+=getsum(m)-getsum(stu[i].y);
           // printf("%lld\n",ans);
            change(stu[i].y);
        }
        printf("Test case %lld: %lld\n",++cnt,ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值