一個簡單的詢問「莫隊」
阿新 • • 發佈:2020-10-25
題目描述
思路分析
- 區間查詢無修改,
看上去就很莫隊 - 但是一個詢問有四個端點,莫隊處理不了,所以嘗試把柿子拆開。最容易想到的就是先利用差分,把 \(get(l,r,x)\) 拆成 \(get(1,r,x)-get(1,l-1,x)\),然後原來的柿子就成了這樣:
- 將每次詢問拆成上面四個部分,就可以將四個端點的詢問改成兩個端點(因為左端點的 \(1\)
- 對於每組形如 \(get(1,l,x)×get(1,r,x)\) 的形式,分別記錄左邊那個 \(get\) 和右邊的那個 \(get\) 的每個數出現的次數(字首和形式),開兩個陣列 \(cnt1\),\(cnt2\),我們以移動左端點為例,這時候每次移動,左半部分對應的 \(cnt1[x]\) 都會加一或減一,由於相乘的形式,答案的變化量則是右半部分的 \(cnt2[x]\)。
- 統計的時候按字首和方式統計,所以修改和正常的莫隊有些區別
然後就又稀裡糊塗地成了最優解
\(Code\)
#include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #define N 50010 #define R register #define ll long long using namespace std; inline int read(){ int x = 0,f = 1; char ch = getchar(); while(ch>'9'||ch<'0'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();} return x*f; } int n,m,len,a[N],belong[N],cnt1[N],cnt2[N],tot; ll nowans,ans[N]; struct query{ int l,r,id,flag; query(){} query(int _l,int _r,int _id,int _flag){l = _l,r = _r,id = _id,flag = _flag;} inline bool operator <(const query &a)const{ return belong[l]==belong[a.l] ? (belong[l]&1 ? r < a.r : r > a.r) : belong[l] < belong[a.l]; } }q[N<<2]; int main(){ n = read(); len = sqrt(n); for(R int i = 1;i <= n;i++)a[i] = read(),belong[i] = (i-1)/len+1; m = read(); for(R int i = 1;i <= m;i++){ int l1 = read(),r1 = read(),l2 = read(),r2 = read(); q[++tot] = query(r1,r2,i,1);//按柿子拆成四個 q[++tot] = query(r1,l2-1,i,-1); q[++tot] = query(l1-1,r2,i,-1); q[++tot] = query(l1-1,l2-1,i,1); } for(R int i = 1;i <= tot;i++)if(q[i].l > q[i].r)swap(q[i].l,q[i].r); sort(q+1,q+1+tot); int l = 0,r = 0; for(R int i = 1;i <= tot;i++){ while(l<q[i].l)cnt1[a[++l]]++,nowans += cnt2[a[l]];//計算貢獻的變化量 while(l>q[i].l)cnt1[a[l]]--,nowans -= cnt2[a[l--]]; while(r<q[i].r)cnt2[a[++r]]++,nowans += cnt1[a[r]]; while(r>q[i].r)cnt2[a[r]]--,nowans -= cnt1[a[r--]]; ans[q[i].id] += nowans*q[i].flag; } for(R int i = 1;i <= m;i++)printf("%lld\n",ans[i]); return 0; }