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

分析:

题意:
       约翰是个农民,他养了一群牛,一群喜欢吃三叶草的牛。所有的三叶草都长在一条直线上。
       有N头牛,没头牛都有特别喜欢的三叶的范围——记为[s,e],不同的牛区间可能有重叠。
       如果一头牛i喜欢的范围为[Si,Ei],另外一头牛j喜欢的范围为[Sj,Ej],如果Si<=Sj、Ei>=Ej并且Ei-Si>Ej-Sj,则称牛i比牛j强壮,问这N头牛中,每头牛比它强的牛有多少?

解析:
       开始没有头绪,后来看了大佬的代码才懂的!向大佬们致敬!
       开始我想在线做的,后来想着不对,就离线做。对牛按范围排序!然后用树状数组对左端点更新!简单说来就是这样,不懂的请看代码!

代码:

#include<iostream>
#include<cstdio>
#include<algorithm> 
#define N 100005

using namespace std;

struct node{
	int l,r;//l记录这头牛喜欢的左端点,r则为右端点
	int id;//记录这头牛的id
};

node book[N];//离线记录
int tree[N];//构造树状数组
int sum[N];//记录第i头牛有几头牛比他强

int n,Max;//Max记录最大的右端点

bool cmp(node a,node b)
{
	if(a.r==b.r)
		return a.l<b.l;
	return a.r>b.r;
}

int lowbit(int x)
{
	return x&-x;
}

void updata(int x)
{
	while(x<=Max)
	{
		tree[x]+=1;
		x+=lowbit(x);
	}
}

int Sum(int x)
{
	int count=0;
	while(x>0)
	{
		count+=tree[x];
		x-=lowbit(x);
	}
	return count;
}

int main()
{
	while(cin>>n&&n)
	{
		Max=-1;
		for(int i=1;i<=n;i++)
		{
			scanf("%d%d",&book[i].l,&book[i].r);
			book[i].id=i;
			if(book[i].r>Max)
				Max=book[i].r;
		}
		sort(book+1,book+n+1,cmp);
		sum[book[1].id]=0;
		updata(book[1].l+1);
		for(int i=2;i<=n;i++)
		{
			if(book[i].r==book[i-1].r&&book[i].l==book[i-1].l)
				sum[book[i].id]=sum[book[i-1].id];
			else
				sum[book[i].id]=Sum(book[i].l+1);
			updata(book[i].l+1);
		}
		printf("%d",sum[1]);
		tree[1]=sum[1]=0;
		for(int i=2;i<=n;i++)
		{
			printf(" %d",sum[i]);
			tree[i]=sum[i]=0;
		}
		printf("\n");
	}
	return 0;
}
发布了46 篇原创文章 · 获赞 16 · 访问量 406

猜你喜欢

转载自blog.csdn.net/weixin_43357583/article/details/105097471
今日推荐