数列分块入门 1(LibreOj-6277)
生活随笔
收集整理的這篇文章主要介紹了
数列分块入门 1(LibreOj-6277)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【題目描述】
給出一個長為 n 的數列,以及 n 個操作,操作涉及區間加法,單點查值。
【輸入格式】
第一行輸入一個數字 n。
第二行輸入 n?個數字,第 i 個數字為 ai,以空格隔開。
接下來輸入 n 行詢問,每行輸入四個數字 opt、l、r、c,以空格隔開。
若 opt=0,表示將位于 [l,r] 的之間的數字都加 c。
若 opt=1,表示詢問 a[r] 的值(l 和 c 忽略)。
【輸出格式】
對于每次詢問,輸出一行一個數字表示答案。
【樣例】
樣例輸入
4
1 2 2 3
0 1 3 1
1 0 1 0
0 1 2 2
1 0 2 0
樣例輸出
2
5
【數據范圍與提示】
對于 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 = 100000+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;int block;//block為塊的長度 int a[N];//存放數列元素 int pos[N],tag[N];//pos記錄第i個元素在第幾個塊中,tag為操作標記 void add(int L,int R,int x){for(int i=L;i<=min(pos[L]*block,R);i++)//統計左區間a[i]+=x;if(pos[L]!=pos[R])//如果存在右區間才遍歷,防止重復計算for(int i=(pos[R]-1)*block+1;i<=R;i++)//統計右區間a[i]+=x;for(int i=pos[L]+1;i<=pos[R]-1;i++)//統計整塊區間tag[i]+=x; } int main(){int n;scanf("%d",&n);for(int i=1;i<=n;i++)scanf("%d",&a[i]);block=sqrt(n);//塊的長度for(int i=1;i<=n;i++)//第i個元素在第幾塊中pos[i]=(i-1)/block+1;for(int i=1;i<=n;i++){int op;int left,right,x;scanf("%d",&op);scanf("%d%d%d",&left,&right,&x);if(op==0)add(left,right,x);elseprintf("%d\n",a[right]+tag[pos[right]]);}return 0; }?
總結
以上是生活随笔為你收集整理的数列分块入门 1(LibreOj-6277)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一维战舰(51Nod-1521)
- 下一篇: Powerful array(CF-86