树状数组 cows

来源:互联网 发布:淘宝e宠商城旗舰店 编辑:程序博客网 时间:2024/06/06 03:59
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 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 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 <= 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
31 20 33 40
Sample Output
1 0 0
按e从大到小排序  然后把 s插入  那肯定是s小的在前面并且在前面的e也比s大 如果s,e相同那他和前一头牛的值相等 
注意的是第i头牛是没排序 时的第i头 标记一下!1111111
#include <iostream>#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;const int maxn=100005;int n;struct cow{    int s,e,val;}b[maxn];int a[maxn],cnt[maxn];int cmp(cow a,cow b){    if(a.e!=b.e)    return a.e>b.e;    else    return a.s<b.s;}int lowbit(int i){    return i&(-i);}int update(int i,int x){    while(i<=n)    {        a[i]=a[i]+x;        i=i+lowbit(i);    }}int query(int i){    int sum=0;    while(i>0)    {        sum+=a[i];        i=i-lowbit(i);    }    return sum;}int main(){    while(~scanf("%d",&n)&&n)    {        memset(b,0,sizeof(b));        memset(cnt,0,sizeof(cnt));        memset(a,0,sizeof(a));        for(int i=0;i<n;i++)        {            scanf("%d%d",&b[i].s,&b[i].e);            b[i].s++;            b[i].e++;            b[i].val=i;        }        sort(b,b+n,cmp);        update(b[0].s,1);        for(int i=1;i<n;i++)        {            if((b[i-1].s==b[i].s)&&(b[i-1].e==b[i].e))            cnt[b[i].val]=cnt[b[i-1].val];            else cnt[b[i].val]=query(b[i].s);            update(b[i].s,1);        }        printf("%d",cnt[0]);        for(int i=1;i<n;i++)        printf(" %d",cnt[i]);        printf("\n");    }    return 0;}


原创粉丝点击