【CF1194E】Count The Rectangles【类扫描线】【单调性】【树状数组】
傳送門
題意:給定NNN條與坐標(biāo)軸平行的線段,保證不垂直的線段沒有交點(diǎn),求一共構(gòu)成多少個矩形(以線段交點(diǎn)為頂點(diǎn))。
1≤N≤50001\leq N\leq50001≤N≤5000
顯然是個數(shù)據(jù)結(jié)構(gòu)亂搞題。
直覺告訴我們先枚舉一條線段。
假如我們枚舉矩形的上邊界,我們希望找到可以構(gòu)成矩形的其他邊。
如果我們找下邊界,那左右邊界即要穿過上下邊界,還要在上下邊界的交集內(nèi),很難維護(hù)。
所以我們可以找左右邊界。
我們發(fā)現(xiàn)和上邊界相交的豎直線都可以當(dāng)左右邊界,所以先找一遍存起來。
這樣我們只需要計(jì)算下邊界和多少個豎直線相交,n(n?1)/2n(n-1)/2n(n?1)/2即可
但是我們還需要滿足下邊界在豎直線下端點(diǎn)的上面
然后我們發(fā)現(xiàn)這個可以用單調(diào)性搞掉
即開始時(shí)水平線按高度排序,把豎直線丟進(jìn)去后按下端點(diǎn)的高度排序,枚舉下面的水平線作為下邊界,如果在豎直線下端點(diǎn)的下面就丟掉,然后區(qū)間查詢豎直線的個數(shù)。
樹狀數(shù)組維護(hù)即可。
復(fù)雜度O(n2logn)O(n^2logn)O(n2logn)
#include <iostream> #include <cstdio> #include <cstring> #include <cctype> #include <algorithm> #define MAXN 5005 using namespace std; typedef long long ll; struct line{int p,l,r;}hor[MAXN],ver[MAXN],pos[MAXN]; int cnt1,cnt2; const int N=10005; struct BIT {int s[MAXN<<1];inline int lowbit(const int& x){return x&-x;}inline void modify(int x,const int& v){x+=MAXN;for (;x<=N;s[x]+=v,x+=lowbit(x));}inline int query(int x){int ans=0;x+=MAXN;for (;x;ans+=s[x],x-=lowbit(x));return ans;}; }bit; inline bool cmp1(const line& a,const line& b){return a.p<b.p;} inline bool cmp2(const line& a,const line& b){return a.r<b.r;} int main() {int n;scanf("%d",&n);for (int i=1;i<=n;i++){int x1,y1,x2,y2;scanf("%d%d%d%d",&x1,&y1,&x2,&y2);if (x1>x2) swap(x1,x2);if (y1>y2) swap(y1,y2);if (x1==x2) ver[++cnt2]=(line){x1,y1,y2};else hor[++cnt1]=(line){y1,x1,x2};}sort(hor+1,hor+cnt1+1,cmp1);ll ans=0;for (int i=1;i<=cnt1;i++){int tot=0;for (int j=1;j<=cnt2;j++)if (ver[j].l<=hor[i].p&&hor[i].p<=ver[j].r&&hor[i].l<=ver[j].p&&ver[j].p<=hor[i].r)pos[++tot]=ver[j];sort(pos+1,pos+tot+1,cmp2);for (int j=1;j<=tot;j++) bit.modify(pos[j].p,1);int now=1;for (int j=i+1;j<=cnt1;j++){while (now<=tot&&pos[now].r<hor[j].p) bit.modify(pos[now].p,-1),++now;int t=bit.query(hor[j].r)-bit.query(hor[j].l-1);ans+=(ll)t*(t-1)/2;}while (now<=tot) bit.modify(pos[now].p,-1),++now;}cout<<ans;return 0; }總結(jié)
以上是生活随笔為你收集整理的【CF1194E】Count The Rectangles【类扫描线】【单调性】【树状数组】的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 美的系双 11 全网总销售额连续 11
- 下一篇: 【HAOI2015】按位或【Min-Ma