Cows
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 19673 | Accepted: 6699 |
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.
这题只要将给的数据存起来,然后用树状数组来表示,将所给的数据排序,如程序所示,
然后只要根据S来找就可以。
1 #include <iostream> 2 #include <algorithm> 3 #include <cstring> 4 #include <cstdio> 5 #define N 100005 6 #define mem(a) memset(a,0,sizeof(a)) 7 using namespace std; 8 struct Node{ 9 int x,y,id; 10 }; 11 int val[N]; 12 int lowbit(int a){ 13 return a&(-a); 14 } 15 int tree[N]; 16 Node node[N]; 17 18 void update(int x){ 19 while(x<=N){ 20 tree[x]++; 21 x+=lowbit(x); 22 } 23 } 24 25 bool cmp(Node a,Node b){ 26 if(a.y==b.y) 27 return a.x<b.x; 28 return a.y>b.y; 29 } 30 int query(int x){ 31 int sum=0; 32 while(x>0){ 33 sum+=tree[x]; 34 x-=lowbit(x); 35 } 36 return sum; 37 } 38//void test(){ 39// cout<<"***"<<endl; 40// } 41 int main() { 42 int n; 43 while(scanf("%d",&n)&&n){ 44 mem(tree); 45 // mem(node); 46 mem(val); 47 for(int i=0;i<n;i++){ 48 scanf("%d%d",&node[i].x,&node[i].y); 49 node[i].id=i; 50 node[i].x++; 51 node[i].y++; 52 } 53 sort(node,node+n,cmp); 54 val[node[0].id]=query(node[0].x); 55 update(node[0].x); 56 57 for(int i=1;i<n;i++){ 58 if(node[i].x==node[i-1].x&&node[i].y==node[i-1].y){ 59 val[node[i].id]=val[node[i-1].id]; 60 }else{ 61 val[node[i].id]=query(node[i].x); 62 }update(node[i].x); 63 } 64 65 // test(); 66 for(int i=0;i<n;i++){ 67 if(i!=n-1) 68 printf("%d ",val[i]); 69 else 70 printf("%d\n",val[i]); 71 } 72 } 73 return 0; 74 }