POJ 2481 Cows【树状数组】

Description

Farmer John's cows have discovered that the clover growing along the ridge of the hill (which we can think of as a one-dimensional number line) in his field is particularly good. 

Farmer John has N cows (we number the cows from 1 to N). Each of Farmer John's N cows has a range of clover that she particularly likes (these ranges might overlap). The ranges are defined by a closed interval [S,E]. 

But some cows are strong and some are weak. Given two cows: cow i and cow j, their favourite clover range is [Si, Ei] and [Sj, Ej]. If Si <= Sj and Ej <= Ei and Ei - Si > Ej - Sj, we say that cow i is stronger than cow j

For each cow, how many cows are stronger than her? Farmer John needs your help!

Input

The input contains multiple test cases. 
For each test case, the first line is an integer N (1 <= N <= 10 5), which is the number of cows. Then come N lines, the i-th of which contains two integers: S and E(0 <= S < E <= 10 5) specifying the start end location respectively of a range preferred by some cow. Locations are given as distance from the start of the ridge. 

The end of the input contains a single 0.

Output

For each test case, output one line containing n space-separated integers, the i-th of which specifying the number of cows that are stronger than cow i

Sample Input

3

1 2

0 3

3 4

0

Sample Output

1 0 0

题意给出每头牛的S[]与E[]当Si<=Sj&&Ej<=Ei说明i牛比j牛强壮,找出比i(1...n)强壮的牛的个数
思路:还是应用树状数组,将E[]升序排列,S[]降序排列,注意点就是坐标x会有0出现,所以坐标x+1,避免死循环

代码如下:

#include<stdio.h>

#include<string.h>

#include<iostream>

#include<algorithm>

using namespace std; 

#define N 100005

int c[N], total[N], n, maxx; 

struct coww

{

    int s, e, num;

}cow[N]; 

int cmp(coww x, coww y)

{

    if(x.e!=y.e)

        return x.e>y.e;

    return x.s<y.s;

}    

int Lowbit(int t)  

{

    return t&(-t);

}

int Sum(int end)  

{

    int sum=0;

    while(end>0)

    {

        sum+=c[end];

        end-=Lowbit(end);

    }

    return sum;

}

void add(int li) 

{

    while(li<=maxx)

    {

           c[li]+=1;

        li+=Lowbit(li);

    }

}           

int main()

{

    int i, j;

    while(scanf("%d", &n)!=EOF)

    {

        if(n==0)    break;

        memset(c, 0, sizeof(c)); 

        memset(total, 0, sizeof(total));

        maxx=0; 

        for(i=1; i<=n; i++)

        {

            scanf("%d%d", &cow[i].s, &cow[i].e);

            cow[i].s++, cow[i].e++; 

            cow[i].num=i;

            maxx=max(maxx, cow[i].s); 

        }

        sort(cow+1, cow+n+1, cmp);

        for(i=1; i<=n; i++)

        { 

            add(cow[i].s);

            if(cow[i].s==cow[i-1].s&&cow[i].e==cow[i-1].e&&i>1)

                 total[cow[i].num]=total[cow[i-1].num];

            else 

                total[cow[i].num]=Sum(cow[i].s)-1;

        } 

        for(i=1; i<n; i++)

            printf("%d ", total[i]);

        printf("%d\n", total[n]);

    }

}

 

 

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