poj 2481 Cows 树状数组解法,详细解析。

Cows

Time Limit:3000MSMemory Limit:65536K

Total Submissions:13445Accepted:4448

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: cowiand 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 cowiis 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

31 20 33 40

Sample Output

1 0 0

Hint

Huge input and output,scanf and printf is recommended.

Source

,Author:Mathematica@ZSU

莫名的感觉自己越来越笨了,哎,,可能是做题少了吧,,以后要疯狂做题,这题的本意就是求一个区间的真子集。首先你得自己画几条长短不一的线,子集推一下

1——————

2—————–

3 —————————

4———

5 ———–

6——————

自己琢磨琢磨这就会发现,当这样排列时,问题就变的简单了:

1——————

6——————

5 ———–

2—————–

4———

这是按什么样的规则排列的呢?

1,首先按E做降序排列

2,如果E相同,S按升序排列。

为什么这样排列就使问题简单了呢?

因为此时只需考虑S值,如果当前牛的测验值为[s, e],那么比它强壮的牛的个数,就等于排列在它前面的,sum值在[0,s]区间的牛数量(E相等的话为[0,s-1])。怎么求S,就是树状数组的事情了。

#include <cstdio>#include <cstring>#include <algorithm>#define MAX 100100 using namespace std ;struct Interval{int s , e , id;}in[MAX];int t[MAX] , ans[MAX]; bool cmp(Interval a , Interval b){if(a.e!=b.e){return a.e>b.e ;}else{return a.s<b.s ;}}int lowbit(int x){return x&(-x) ;}void update(int pos){while(pos<MAX){++t[pos] ;pos += lowbit(pos) ;}}int query(int pos){int count = 0 ;while(pos>0){count += t[pos] ;pos -= lowbit(pos) ;}return count ;}int main(){int n ;while(scanf("%d",&n) && n){memset(t,0,sizeof(t)) ;for(int i = 1 ; i <= n ; ++i){in[i].id = i ;scanf("%d%d",&in[i].s,&in[i].e) ;++in[i].s,++in[i].e;//这步是考虑到树状数组的 0 陷阱 }sort(in+1,in+n+1,cmp) ;for(int i = 1 ; i <= n ; ++i){int num ;if(in[i].e == in[i-1].e && in[i].s == in[i-1].s)//注意这步,当区间相同时,比他们强壮的牛应该相等。num = ans[in[i-1].id] ;else num = query(in[i].s) ;update(in[i].s) ;ans[in[i].id] = num;}for(int i = 1 ; i <= n ; ++i){printf("%d ",ans[i]) ;}printf("\n") ;}return 0 ;}

莫找借口失败,只找理由成功。(不为失败找理由,要为成功找方法

poj 2481 Cows 树状数组解法,详细解析。

相关文章:

你感兴趣的文章:

标签云: