Japan POJ - 3067(树状数组)

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行给出连边,问共有多少交叉点;
思路: 交叉点产生的条件:用图解释:
当一条边的左端点高于另一条边的左端点,并且其右端点低于另一条边的右端点
Japan POJ - 3067(树状数组)_第1张图片
我们将每条边的按左端点从小到大排序,左端点相同按右端点从小到大排序;
处理完后将题中例子画出来:
Japan POJ - 3067(树状数组)_第2张图片
Japan POJ - 3067(树状数组)_第3张图片
左边从上到下遍历时,当其右端点存在之前连得边的右端点比该边的右端点小,可以遍历左端点时将其右端点标记加一,同时查找此边的右端点之前有几个比他小的即可;用树状数组维护;
代码

//#include
#include
#include
#include
#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;
}

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