数列分块入门 4(LibreOj-6280)
生活随笔
收集整理的這篇文章主要介紹了
数列分块入门 4(LibreOj-6280)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【題目描述】
給出一個長為 n 的數列,以及 n 個操作,操作涉及區間加法,區間求和。
【輸入格式】
第一行輸入一個數字 n。
第二行輸入 n?個數字,第 i 個數字為 ai,以空格隔開。
接下來輸入 n 行詢問,每行輸入四個數字 opt、l、r、c,以空格隔開。
若 opt=0,表示將位于 [l,r] 的之間的數字都加 c。
若 opt=1,表示詢問位于 [l,r] 的所有數字的和 mod(c+1)。
【輸出格式】
對于每次詢問,輸出一行一個數字表示答案。
【樣例】
樣例輸入
4
1 2 2 3
0 1 3 1
1 1 4 4
0 1 2 2
1 1 2 4
樣例輸出
1
4
【數據范圍與提示】
對于 100%?的數據,1<=n<=50000,-2^31<=other,ans<=2^31-1。
【源代碼】
#include<iostream> #include<cstdio> #include<cstdlib> #include<string> #include<cstring> #include<cmath> #include<ctime> #include<algorithm> #include<utility> #include<stack> #include<queue> #include<vector> #include<set> #include<map> #include<bitset> #define EPS 1e-9 #define PI acos(-1.0) #define INF 0x3f3f3f3f #define LL long long const int MOD = 1E9+7; const int N = 1000000+5; const int dx[] = {-1,1,0,0,-1,-1,1,1}; const int dy[] = {0,0,-1,1,-1,1,-1,1}; using namespace std;LL block,sum;//block為塊的長度,sum為塊的個數 LL a[N];//存放數列元素 LL pos[N],tag[N];//pos記錄第i個元素在第幾個塊中,tag為操作標記 LL ans[N];//維護整塊和 void init(LL n){block=sqrt(n);//塊的長度sum=n/block;//塊個數if(n%block)sum++;for(LL i=1;i<=n;i++)//第i個元素在第幾塊中pos[i]=(i-1)/block+1; } void work(LL L,LL R,LL x){//維護整塊和LL start=0;for(LL i=L;i<=R;i++)start+=a[i];ans[x]=start; } void update(LL L,LL R,LL x){for(LL i=L;i<=min(pos[L]*block,R);i++){//左邊的邊角料ans[pos[i]]+=x;a[i]+=x;}if(pos[L]!=pos[R]){//存在右區間才遍歷,防止重復計算for(LL i=(pos[R]-1)*block+1;i<=R;i++){//右邊的邊角料ans[pos[i]]+=x;a[i]+=x;}}for(LL i=pos[L]+1;i<=pos[R]-1;i++){//中間的整塊tag[i]+=x;} } LL query(LL L,LL R,LL mod){LL res=0;for(LL i=L;i<=min(pos[L]*block,R);i++){//左邊的邊角料res+=a[i]+tag[pos[i]];}if(pos[L]!=pos[R]){//存在右區間才遍歷,防止重復計算for(LL i=(pos[R]-1)*block+1;i<=R;i++){//右邊的邊角料res+=a[i]+tag[pos[i]];}}for(LL i=pos[L]+1;i<=pos[R]-1;i++){//中間的整塊進行二分查找res+=ans[i]+tag[i]*block;}return res%mod; } int main(){LL n;scanf("%lld",&n);for(LL i=1;i<=n;i++)scanf("%lld",&a[i]);init(n);for(LL i=1;i<=sum;i++)//傳入塊的左右邊界與編號work((i-1)*block+1,i*block,i);for(LL i=1;i<=n;i++){LL op;LL left,right,x;scanf("%lld",&op);scanf("%lld%lld%lld",&left,&right,&x);if(op==0)update(left,right,x);else if(op==1)printf("%lld\n",query(left,right,x+1));}return 0; }?
總結
以上是生活随笔為你收集整理的数列分块入门 4(LibreOj-6280)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 营救(洛谷-P1396)
- 下一篇: 数列极差(信息学奥赛一本通-T1427)