Cows
Time Limit: 3000MS
Memory Limit: 65536K
Total Submissions: 13445
Accepted: 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: 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
Hint
Huge input and output,scanf and printf is recommended.
Source
POJ Contest,Author:Mathematica@ZSU
莫名的感覺自己越來越笨了,哎,可能是做題少了吧,,以後要瘋狂做題,這題的本意就是求一個區間的真子集。首先你得自己畫幾條長短不一的線,子集推一下
:
1 ------------------
2 -----------------
3 ---------------------------
4 ---------
5 -----------
6 ------------------
自己琢磨琢磨這就會發現,當這樣排列時,問題就變的簡單了:
3
---------------------------
1
------------------
6
------------------
5
-----------
2
-----------------
4
---------
這是按什麼樣的規則排列的呢?
1,首先按E做降序排列
2,如果E相同,S按升序排列。
為什麼這樣排列就使問題簡單了呢?
因為此時只需考慮S值,如果當前牛的測驗值為[s,
e],那麼比它強壯的牛的個數,就等於排列在它前面的,sum值在[0,s]區間的牛數量(E相等的話為[0,s-1])。怎麼求S,就是樹狀數組的事情了。
#include
#include
#include
#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.s0)
{
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 ;
}