luogu P4135 作詩
阿新 • • 發佈:2018-12-26
背景:
槓了兩天。
卡常。
不開
只有
。
我的時間複雜度是:
然而發現跑
的時間複雜度是:
。
我驚了(我太菜)。
題目傳送門:
https://www.luogu.org/problemnew/show/P4135
題意:
個數,每一次詢問
區間的出現偶數次的正整數的次數。
強制線上。(不然就是莫隊的水題了)。
思路:
只能分塊了。
毒瘤出題人。
考慮預處理。
表示第
塊到第
塊的答案。
可以預處理出來(
)。
於是對於一個詢問的區間,不妨分為三個部分:兩個小塊和中間完整的大塊。
對於那一個大塊,我們可以
出解。
有人會問:兩個小塊也會影響答案啊,中間求出來的有什麼用嗎?
考慮做兩個小塊的時間複雜度是
,在做的時候,不妨讓其與中間的那一塊聯合求解,因為你可以在處理出每一個值所有的位置,再帶上一個二分,就可以知道在當前這一塊內的個數。再像預處理一般求解即可。
細節較多,可以認真思考。
程式碼:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
vector<int> list[100010];
queue<int> F;
int n,m,q,block;
int a[100010],tot[100010];
int belong[100010],l[10010],r[10010],f[500][500];//第i塊到第j塊的答案
void init()
{
for(int i=1;i<=belong[n];i++)
{
int tmp=0;
for(int j=l[i];j<=n;j++)
{
tot[a[j]]++;
if((tot[a[j]]&1)&&tot[a[j]]!=1) tmp--;
if(!(tot[a[j]]&1)) tmp++;
f[i][belong[j]]=tmp;
}
memset(tot,0,sizeof(tot));
}
}
int calc(int x,int y,int id)
{
return upper_bound(list[id].begin(),list[id].end(),y)-lower_bound(list[id].begin(),list[id].end(),x);
}
int solve(int x,int y)
{
int ans=0;
while(!F.empty()) F.pop();
if(belong[x]==belong[y])
{
for(int i=x;i<=y;i++)
{
if(!tot[a[i]]) F.push(a[i]);
tot[a[i]]++;
}
while(!F.empty())
{
if(!(tot[F.front()]&1)) ans++;
tot[F.front()]=0;
F.pop();
}
}
else
{
ans=f[belong[x]+1][belong[y]-1];
for(int i=x;i<=r[belong[x]];i++)
{
if(!tot[a[i]]) F.push(a[i]);
tot[a[i]]++;
}
for(int i=y;i>=l[belong[y]];i--)
{
if(!tot[a[i]]) F.push(a[i]);
tot[a[i]]++;
}
while(!F.empty())
{
int now=F.front();
F.pop();
int sum=calc(x,y,now),sum1=sum-tot[now],sum2=tot[now];
if(sum1&1) ans+=(sum2&1);
else if(sum1) ans-=(sum2&1);
else ans+=((sum2&1)^1);
}
for(int i=x;i<=r[belong[x]];i++)
tot[a[i]]=0;
for(int i=y;i>=l[belong[y]];i--)
tot[a[i]]=0;
}
return ans;
}
int main()
{
int x,y;
scanf("%d %d %d",&n,&m,&q);
block=sqrt(n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
list[a[i]].push_back(i);
belong[i]=i/block+1;
if(belong[i]!=belong[i-1]) l[belong[i]]=i,r[belong[i-1]]=i-1;
}
r[belong[n]]=n;
init();
int last=0;
for(int i=1;i<=q;i++)
{
scanf("%d %d",&x,&y);
x=(x+last)%n+1,y=(y+last)%n+1;
if(x>y) swap(x,y);
printf("%d\n",last=solve(x,y));
}
}