1. 程式人生 > >BZOJ 1878: [SDOI2009]HH的項鏈 | 莫隊

BZOJ 1878: [SDOI2009]HH的項鏈 | 莫隊

main problem 題解 == pri hh的項鏈 lin 用兩個 online

題解:

http://www.lydsy.com/JudgeOnline/problem.php?id=1878


題解:

莫隊板子題

核心思想是對區間的詢問離線之後按照合理的順序來優化復雜度

一般的做法是先分塊,以左端點所在塊為第一關鍵字,右端點位置為第二關鍵字排序

用兩個指針來跑,這樣可以證明的是時間復雜度為O(n√n)

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#define N 50005
#define M 1000005
#define Q 200005
using
namespace std; int n,m,S,l,r,tl,tr,tot,ans[Q],a[N],cnt[M]; struct node { int l,r,bl,id; bool operator < (const node &x)const { return bl<x.bl || bl==x.bl && r<x.r; } }q[Q]; int main() { scanf("%d",&n);S=sqrt(n); for (int i=1;i<=n;i++) scanf(
"%d",a+i); scanf("%d",&m); for (int i=1;i<=m;i++) { scanf("%d%d",&l,&r); q[i].id=i;q[i].l=l;q[i].r=r;q[i].bl=(l-1)/S+1; } sort(q+1,q+1+m); for (int i=1;i<=m;i++) { l=q[i].l,r=q[i].r; while (tl<l) if (!--cnt[a[tl++]]) tot--; while (tl>l) if
(!cnt[a[--tl]]++) tot++; while (tr<r) if (!cnt[a[++tr]]++) tot++; while (tr>r) if (!--cnt[a[tr--]]) tot--; ans[q[i].id]=tot; } for (int i=1;i<=m;i++) printf("%d\n",ans[i]); return 0; }

BZOJ 1878: [SDOI2009]HH的項鏈 | 莫隊