題目描述
衆所周知,模數的hash會產生衝突。例如,如果模的數p=7
,那麼4
和11
便衝突了。
B君對hash衝突很感興趣。他會給出一個正整數序列value[]
。
自然,B君會把這些數據存進hash池。第value[k]
會被存進(k%p)
這個池。這樣就能造成很多衝突。
B君會給定許多個p
和x
,詢問在模p
時,x
這個池內**數的總和
**。
另外,B君會隨時更改value[k]
。每次更改立即生效。
保證1<=p<n1<=p<n.
輸入格式
第一行,兩個正整數n,m
,其中n
代表序列長度,m
代表B君的操作次數。
第一行,n
個正整數,代表初始序列。
接下來m
行,首先是一個字符cmd
,然後是兩個整數x,y
。
-
若
cmd='A'
,則詢問在模x
時,y
池內數的總和。 -
若
cmd='C'
,則將value[x]
修改爲y
。
輸出格式
對於每個詢問輸出一個正整數,進行回答。
輸入輸出樣例
輸入 #1複製
10 5 1 2 3 4 5 6 7 8 9 10 A 2 1 C 1 20 A 3 1 C 5 1 A 5 0
輸出 #1複製
25 41 11
說明/提示
樣例解釋
A 2 1
的答案是1+3+5+7+9=25
.
A 3 1
的答案是20+4+7+10=41
.
A 5 0
的答案是1+10=11
.
數據規模
對於10%
的數據,有n<=1000,m<=1000
.
對於60%
的數據,有n<=100000.m<=100000
.
對於100%
的數據,有n<=150000,m<=150000
.
保證所有數據合法,且1<=value[i]<=1000
.
。。。。。數據有點弱,直接暴力只會T一個點。那麼先給個暴力的代碼:
#include <bits/stdc++.h>
using namespace std;
const int mac=1e6+10;
int a[mac];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int n,m;
cin>>n>>m;
for (int i=1; i<=n; i++)
cin>>a[i];
for (int i=1; i<=m; i++){
char s[2];
int x,y;
cin>>s>>x>>y;
if (s[0]=='A') {
int ans=0;
for (int j=y; j<=n; j+=x) ans+=a[j];
cout<<ans<<endl;
}
else {
a[x]=y;
}
}
return 0;
}
T了一個的點是死活都過不去,除了打表。。。。那麼我們就要優化我們的算法了。按照分塊一貫的尿性就是將n處理成sqrt(n)。有什麼用呢?簡單來講這一題可以預處理,暴力預處理的複雜度是n^2,我們將模降成sqrt(n)那麼複雜度就會下降:
for (int i=1; i<=sqrt(n); i++)//枚舉模數
for (int j=1; j<=n; j++)
ans[i][j%i]+=a[j];
接下來每次詢問就是O(1)複雜度了,修改的時候也是sqrt(n)的複雜度:
for (int j=1; j<=sqrt(n); j++)
ans[j][x%j]-=a[x],ans[j][x%j]+=y;
a[x]=y;
那麼還有一個就是當模大於sqrt(n)的時候,這個我們可以直接暴力求,和上面的T了代碼是一樣的。但由於這個時候模數比較大,大於sqrt(n),所以暴力求的時候的複雜度小於sqrt(n)。那麼我們總的複雜度就是O((N+M)*(sqrt(n))。
以下是AC代碼:
#include <bits/stdc++.h>
using namespace std;
const int mac=1.5e5+10;
const int N=sqrt(mac);
int a[mac];
int ans[mac][N];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int n,m;
cin>>n>>m;
for (int i=1; i<=n; i++)
cin>>a[i];
for (int i=1; i<=sqrt(n); i++)
for (int j=1; j<=n; j++)
ans[i][j%i]+=a[j];
for (int i=1; i<=m; i++){
char s[2];
int x,y;
cin>>s>>x>>y;
if (s[0]=='A') {
if (x<=sqrt(n)) cout<<ans[x][y]<<endl;
else {
int sum=0;
for (int j=y; j<=n; j+=x)
sum+=a[j];
cout<<sum<<endl;
}
}
else {
for (int j=1; j<=sqrt(n); j++)
ans[j][x%j]-=a[x],ans[j][x%j]+=y;
a[x]=y;
}
}
return 0;
}