poj2481 Cows

Cows
Time Limit: 3000MS   Memory Limit: 65536K
Total 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: 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 iis 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

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 200005
using 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);
	}
}


你可能感兴趣的:(poj)