1. 程式人生 > >2481 Cows

2481 Cows

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

給出每隻牛吃草區間,若a吃草區間大於b吃草區間,則a比b強壯。

求出每隻牛比它強壯的牛的個數。

先按每隻牛 吃草區間的右端點從大到小排序,求所有左端點的正序對的個數。

求正序對用樹狀陣列。

細節處理:

範圍+1,防止樹狀數組裡出現0;
每次找到比當前左區間小的個數的時候還要減一,去除本身;
當遇到兩頭牛的範圍相等時,令答案等於上一頭牛的答案即可,無需求和。

#include <cstdio>
#include <cstring>
#include <algorithm>
#define Lowbit(x) (x&(-x))
#define INF 0x3f3f3f3f
typedef long long int LL;
using namespace std;
const int N = 1e6 + 10;

struct Seg
{
    int l,r,order;
}sam[N];

int cmp(struct Seg a,struct Seg b)
{
    if(a.r==b.r)
        return a.l<b.l;
    return a.r>b.r;
}

int sum(int *C,int p)
{
    int i,ans=0;
    for(i=p; i>0; i-=Lowbit(i))
        ans+=C[i];
    return ans;
}

void Update(int *C,int p,int v)
{
    int i;
    for(i=p; i<N; i+=Lowbit(i))
        C[i]+=v;
}

int main()
{
    int n;
    while(scanf("%d",&n)!=EOF && n)
    {
        int i;
        int ans[N]= {0};
        int C[N]= {0};
        for(i=0; i<n; i++)
        {
            scanf("%d%d",&sam[i].l,&sam[i].r);
            sam[i].l++;
            sam[i].r++;
            sam[i].order=i;
        }
        sort(sam,sam+n,cmp);
        for(i=0; i<n; i++)
        {
            Update(C,sam[i].l,1);
            if(i==0)
                ans[sam[i].order]=sum(C,sam[i].l)-1;
            else
            {
                if(sam[i].l==sam[i-1].l && sam[i].r==sam[i-1].r)
                    ans[sam[i].order]=ans[sam[i-1].order];
                else
                    ans[sam[i].order]=sum(C,sam[i].l)-1;
            }
        }
        for(i=0; i<n; i++)
            printf("%d%c",ans[i],i==n-1?'\n':' ');
    }
    return 0;
}