Newcoder 58 F.序列查詢(莫隊演算法+分塊+連結串列)
阿新 • • 發佈:2018-11-02
Description
給你一個序列 ,有 次,每次查詢一個區間 。
這個區間內一共有 個非空子序列
一個子序列對答案的貢獻是其去重後的和
求所有子序列的貢獻的和
每次的 不一樣
Input
第一行兩個數
第二行 個數表示序列
後面 行每行三個數 表示查詢區間 ,模數是
Output
對於每個查詢輸出一行一個數表示答案
Sample Input
5 5
1 2 2 3 4
1 2 233333
2 3 333333
1 5 203
3 5 15
2 4 8
Sample Output
6
6
176
6
0
Solution
假設數字 在區間 中出現了 次,令 為該區間長度,那麼包含該數字的子序列個數為 ,進而 對該區間的貢獻為
從該貢獻值可以看出 兩者獨立,我們只需要統計出現次數為 的數字之和即可,如此的好處是不同的 值至多 個,用一個線性連結串列來維護這不同的 個出現次數,維護每個出現次數的數字個數和數字之和,那麼每次查詢的結果可以寫成一個 項的求和式
由於模數不同,不能預處理 的次冪,為了加速該求和,對 分塊為 ,其中 ,每次查詢前預處理 以及 ,這樣就可以 得到
時間複雜度
Code
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
namespace fastIO
{
#define BUF_SIZE 100000
//fread -> read
bool IOerror=0;
inline char nc()
{
static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
if(p1==pend)
{
p1=buf;
pend=buf+fread(buf,1,BUF_SIZE,stdin);
if(pend==p1)
{
IOerror=1;
return -1;
}
}
return *p1++;
}
inline bool blank(char ch)
{
return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
}
inline void read(int &x)
{
char ch;
while(blank(ch=nc()));
if(IOerror)return;
int sgn=1;
if(ch=='-')sgn=-1;
for(x=ch-'0';(ch=nc())>='0'&&ch<='9';x=x*10+ch-'0');
x=sgn*x;
}
#undef BUF_SIZE
};
using namespace fastIO;
typedef long long ll;
const int maxn=100005;
int n,m,mm,a[maxn],num[maxn],vis[maxn],pos[maxn],ans[maxn];
ll sum[maxn];
int head,L[maxn],R[maxn];
struct node
{
int l,r,p,id;
bool operator<(const node&b)const
{
if(pos[l]!=pos[b.l])return l<b.l;
return r<b.r;
}
}q[maxn];
void insert(int x)
{
R[x]=head;L[head]=x;head=x;L[x]=0;
}
void erase(int x)
{
if(x==head)head=R[x];
else L[R[x]]=L[x],R[L[x]]=R[x];
}
void update(int x,int v)//表示對第x個元素做刪除(v=-1)或者新增(v=1)
{
if(num[a[x]])
{
sum[num[a[x]]]-=a[x];
vis[num[a[x]]]--;
if(!vis[num[a[x]]])erase(num[a[x]]);
}
num[a[x]]+=v;
if(num[a[x]])
{
sum[num[a[x]]]+=a[x];
vis[num[a[x]]]++;
if(vis[num[a[x]]]==1)insert(num[a[x]]);
}
}
int p,f[1000],g[1000];
int add(int x,int y)
{
x+=y;
if(x>=p)x-=p;
return x;
}
int mul(int x,int y)
{
ll z=1ll*x*y;
return z-z/p*p;
}
void init(int n)
{
f[0]=1;
for(int i=1;i<=mm;i++)f[i]=add(f[i-1],f[i-1]);
g[0]=1;
for(int i=1;i<=n/mm;i++)g[i]=mul(g[i-1],f[mm]);
}
int Pow(int n)
{
return mul(g[n/mm],f[n%mm]);
}
int query(int l,int r,int tp)
{
p=tp;
init(r-l+1);
int ans=0;
for(int i=head;i;i=R[i])
ans=add(ans,mul(sum[i]%p,add(Pow(r-l+1),p-Pow(r-l+1-i))));
return ans;
}
int main()
{
read(n);read(m);
mm=(int)sqrt(n)+1;
for(int i=1;i<=n;i++)
{
read(a[i]);
pos[i]=(i-1)/mm+1;
}
for(int i=0;i<m;i++)
{
read(q[i].l);read(q[i].r);read(q[i].p);
q[i].id=i;
}
sort(q,q+m);
int l=1,r=0;
for(int i=0;i<m;i++)
{
while(r<q[i].r)update(r+1,1),r++;
while(r>q[i].r)update(r,-1),r--;
while(l<q[i].l)update(l,-1),l++;
while(l>q[i].l)update(l-1,1),l--;
ans[q[i].id]=query(q[i].l,q[i].r,q[i].p);
}
for(int i=0;i<m;i++)printf("%d\n",ans[i]);
return 0;
}