poj 2481 Cows 樹狀陣列or線段樹

2021-07-11 05:49:20 字數 1779 閱讀 7851

題意:

給n個區間,問第i個區間是多少個區間的子區間。

分析:

可以吧每乙個線段看成是乙個點,這樣的話就等價於問乙個點的左上方有多少個點?這樣就和stars那題一樣了。

因為是求左上方有多少個點,那麼把所有點按照y從大到小排列,這樣就可以按照順序求出0~x之間有多少個點,就是它左上方的點了。

需要重點的處理。

樹狀陣列:

#include

#include

#include

#include

using

namespace

std;

const

int n=1e5+5;

struct point

p[n];

bool cmp(const point &a,const point &b)

int c[n],ans[n];

int lowbit(int x)

int getsum(int x)

void add(int x)

sort(p,p+n,cmp);

for(int i=0;iif(i&&p[i-1].x==p[i].x&&p[i-1].y==p[i].y)ans[p[i].id]=ans[p[i-1].id];

else

add(p[i].x);

}for(int i=0;i1;i++)

printf("%d ",ans[i]);

printf("%d\n",ans[n-1]);

}return

0;}

線段樹:

用線段樹也是先排序,然後再求區間【0,x】的和,再單點更新。

#include

#include

#include

#include

using

namespace

std;

#define lson l,m,rt<<1

#define rson m+1,r,rt<<1|1

const

int n=1e5+5;

int sum[n<<2];

struct point

p[n];

bool cmp(const point &a,const point &b)

bool cmp2(const point &a,const point &b)

int query(int a,int b,int l,int r,int rt)

void update(int x,int l,int r,int rt)

int m=(l+r)>>1;

if(x<=m)update(x,lson);

else update(x,rson);

pushup(rt);

}int main()

sort(p,p+n,cmp);

for(int i=0;iif(i&&p[i].x==p[i-1].x&&p[i].y==p[i-1].y)p[i].ans=p[i-1].ans;

else p[i].ans=query(0,p[i].x,0,1e5,1);

// printf("%d ",p[i].ans);

update(p[i].x,0,1e5,1);

}sort(p,p+n,cmp2);

for(int i=0;i1;i++)

printf("%d\n",p[n-1].ans);

}return

0;}

POJ 2481 Cows 樹狀陣列

樹狀陣列 其實這題和 poj 2352 或者 就是道用樹狀陣列求逆序數的題目。先排序,我的排序是按照先s從小到大,如果s相等 e從大到小。貌似也沒什麼了。就樹狀陣列吧。include include include include include define inf 0x7fffffff defi...

poj 2481 Cows (樹狀陣列)

小記 之前沒做什麼修改之前,在poj上提交1393ms ac了。然後在hdu的web diy裡提交gnu c 超時了 於是不斷的改,在輸出的地方花費時間太多了。就是為了保證每兩個數之間有乙個空格,然後末尾沒有空格,我在for裡面加了乙個判斷,只要不是末尾就輸出乙個空格。然後就這樣超時了。樹狀陣列全用...

poj 2481 Cows(樹狀陣列)

題意 山坡上長滿三葉草,給定一群牛和他們喜愛的範圍 s,ei 如果一頭牛的s小於等於另一頭牛而e大於等於另一頭牛的,且s和e不同時相等,那麼這頭牛就比另一頭牛強壯。可以先對e從大到小排序,這樣保證遍歷時後出現的牛的上界一定滿足小於等於前面的,這樣只需要判斷他的下界滿不滿足就行,這就想到了用樹狀陣列。...