Cows
Time Limit: 3000MS |
|
Memory Limit: 65536K |
Total Submissions: 15575 |
|
Accepted: 5200 |
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.
题意:每一头牛都有一个适合的食草区间[Si,Ei],如果牛j的区间被包含在牛i的区间内且不相等(Si<=Sj&&Ej<=Ei&& Ei-Si > Ej-Sj ),则表示牛i比牛j强壮。 现在给出n头牛的区间[S,E],按输入顺序输出在牛群中比本身强壮的牛的数量。
题解:我们对牛群按照E从大到小排序(E相同,按照S从小到大排序)。如果对j<i(假设区间不相等),有Sj>=Si,则可以知道牛i比牛j强壮。 但是当牛i与牛j区间相等时怎么办呢? 我们知道两头牛相等时,不能算彼此强壮关系。
即牛i与牛i-1之间,对于前面的牛没有任何影响。当对于后面的更弱的牛有影响。 在解决时,我们可以直接将牛i-1的结果赋值给牛i。
代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define maxn 100010
int bit[maxn],ans[maxn],n;
struct node
{
int s,e,id;
}cow[maxn];
int cmp(node a,node b)
{
if(a.e==b.e)
return a.s<b.s;
return a.e>b.e;
}
int sum(int x)
{
int cnt=0;
while(x>0)
{
cnt+=bit[x];
x-=(x&-x);
}
return cnt;
}
void add(int x)
{
while(x<maxn)
{
bit[x]+=1;
x+=(x&-x);
}
}
int main()
{
int i;
while(scanf("%d",&n)&&n)
{
for(i=0;i<n;++i)
{
scanf("%d%d",&cow[i].s,&cow[i].e);
cow[i].s++;//因为s的值可以为0,防止0的出现
cow[i].id=i;//保存初始位置
}
sort(cow,cow+n,cmp);
memset(ans,0,sizeof(ans));
memset(bit,0,sizeof(bit));
ans[cow[0].id]=0;//排完序的第一个牛
add(cow[0].s);
for(i=1;i<n;++i)
{
if(cow[i].s==cow[i-1].s&&cow[i].e==cow[i-1].e)//两个牛区间完全相同
ans[cow[i].id]=ans[cow[i-1].id];
else
ans[cow[i].id]=sum(cow[i].s);
add(cow[i].s);
}
for(i=0;i<n-1;++i)
printf("%d ",ans[i]);
printf("%d\n",ans[i]);
}
return 0;
}