首页 > 代码库 > POJ 2481 Cows 简单树状数组区间覆盖

POJ 2481 Cows 简单树状数组区间覆盖

点击打开链接

Cows
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 13334 Accepted: 4413

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: cowi and cowj, their favourite clover range is [Si, Ei] and [Sj, Ej]. If Si <= Sj and Ej <= Ei and Ei - Si > Ej - Sj, we say that cowi is stronger than cowj

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 <= 105), which is the number of cows. Then come N lines, the i-th of which contains two integers: S and E(0 <= S < E <= 105) 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 cowi

Sample Input

3
1 2
0 3
3 4
0

Sample Output

1 0 0

Hint

Huge input and output,scanf and printf is recommended.

Source

POJ Contest,Author:Mathematica@ZSU

n头牛,每头牛都有一个范围[s,e],让比它强壮的牛的个数。第i头牛比第j头牛强壮的定义:si<=sj&&ei>=ej&&ei-si>ej-si。
将n头牛按照e从大到小排序,跟据s的值,用树状数组求得答案。
//2156K	1079MS
#include<stdio.h>
#include<algorithm>
#include<string.h>
#define M 100007
using namespace std;
int c[M],ans[M],max_e;
struct Cow
{
    int s,e,id;
}p[M];
int cmp(Cow a,Cow b)
{
    if(a.e==b.e)return a.s<b.s;
    return a.e>b.e;
}
int lowbit(int x)
{
    return x&(-x);
}
void add(int pos,int val)
{
    while(pos<=max_e+1)
    {
        c[pos]+=val;
        pos+=lowbit(pos);
    }
}
int getsum(int pos)
{
    int res=0;
    while(pos>0)
    {
        res+=c[pos];
        pos-=lowbit(pos);
    }
    return res;
}
int main()
{
    int n;
    while(scanf("%d",&n),n)
    {
        max_e=0;
        for(int i=0;i<n;i++)
        {
            scanf("%d%d",&p[i].s,&p[i].e);
            p[i].id=i;
            if(max_e<p[i].e)max_e=p[i].e;
        }
        memset(c,0,sizeof(c));
        sort(p,p+n,cmp);
        for(int i=0;i<n;i++)
        {
            if(p[i].s==p[i-1].s&&p[i].e==p[i-1].e)ans[p[i].id]=ans[p[i-1].id];//与前面的牛属性一样
            else ans[p[i].id]=getsum(p[i].s+1);
            add(p[i].s+1,1);
        }
        for(int i=0;i<n-1;i++)printf("%d ",ans[i]);
        printf("%d\n",ans[n-1]);
    }
    return 0;
}


POJ 2481 Cows 简单树状数组区间覆盖