POJ 2481 Cows(树状数组)

                                                                  Cows
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 17626   Accepted: 5940

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
【分析】给你n个区间,问你对于每个区间,有多少个区间是完全覆盖它的。完全覆盖的意思是若Si <= Sj and Ej <= Ei and Ei - Si > Ej - Sj,那么j就被i完全覆盖。
n<=1e5,所以暴力肯定超时,而树状数组正好可以用于快速的统计个数。首先得排个序,然后模板统计。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#define inf 2e9
#define met(a,b) memset(a,b,sizeof a)
typedef long long ll;
using namespace std;
const int N = 1e5+;
const int M = ;
int n,m;
ll tree[N],ans[N];
struct man{
int s,e,no;
bool operator< (const man &it)const{
if(e==it.e)return s<it.s;
return e>it.e;
}
}a[N];
void add(int k,int num){
while(k<=1e5+){
tree[k]+=num;
//printf("####%lld\n",tree[k]);
k+=k&(-k);
}
}
ll Sum(int k){
ll sum=;
while(k>){
sum+=tree[k];
k-=k&(-k);
}
return sum;
}
int main() {
while(~scanf("%d",&n)&&n){
met(tree,);met(ans,);
for(int i=;i<=n;i++){
scanf("%d%d",&a[i].s,&a[i].e);
a[i].s++;a[i].e++;a[i].no=i;
}
sort(a+,a++n);
for(int i=;i<=n;i++){
ll Ans;
if(a[i].s==a[i-].s&&a[i].e==a[i-].e)Ans=ans[a[i-].no];
else Ans=Sum(a[i].s);
//printf("%d\n",Ans);
ans[a[i].no]=Ans;
add(a[i].s,);
}
printf("%lld",ans[]);
for(int i=;i<=n;i++){
printf(" %lld",ans[i]);
}
printf("\n");
}
return ;
}
上一篇:POJ 3414 Pots(罐子)


下一篇:2018.07.03 POJ 3348 Cows(凸包)