poj2481 Cows

来源:互联网 发布:慈溪市行知职高在哪 编辑:程序博客网 时间:2024/05/17 22:00

Cows
Time Limit: 3000MS Memory Limit: 65536KTotal Submissions: 15187 Accepted: 5054

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 cowiis 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

31 20 33 40

Sample Output

1 0 0

Hint

Huge input and output,scanf and printf is recommended.

Source

POJ Contest,Author:Mathematica@ZSU



首先将所有区间按右端点从大到小排序,依次把每个点左端点的权值加1,并统计1到左端点所有权值的和作为答案。注意两个区间相同的情况。

于是问题转化为单点修改和区间求和,树状数组解决。




#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<cstdlib>#define F(i,j,n) for(int i=j;i<=n;i++)#define D(i,j,n) for(int i=j;i>=n;i--)#define LL long long#define pa pair<int,int>#define MAXN 200005using namespace std;struct data{int l,r,num;}a[MAXN];int n,mx,f[MAXN],ans[MAXN];int read(){int ret=0,flag=1;char ch=getchar();while (ch<'0'||ch>'9'){if (ch=='-') flag=-1;ch=getchar();}while (ch>='0'&&ch<='9'){ret=ret*10+ch-'0';ch=getchar();}return ret*flag;}bool cmp(data x,data y){if (x.r!=y.r) return x.r>y.r;else return x.l<y.l;}void update(int k){for(int i=k;i<=mx;i+=(i&(-i))) f[i]++;}int getsum(int k){int ret=0;for(int i=k;i;i-=(i&(-i))) ret+=f[i];return ret;}int main(){scanf("%d",&n);while (n){mx=0;int tmp=0;memset(f,0,sizeof(f));F(i,1,n) a[i].num=i,a[i].l=read()+1,a[i].r=read()+1,mx=max(mx,a[i].r);sort(a+1,a+n+1,cmp);F(i,1,n){if (a[i].l==a[i-1].l&&a[i].r==a[i-1].r) tmp++;else tmp=1;update(a[i].l);ans[a[i].num]=getsum(a[i].l)-tmp;}F(i,1,n-1) printf("%d ",ans[i]); printf("%d\n",ans[n]);scanf("%d",&n);}}


0 0
原创粉丝点击