区间 (interval)
题目描述
Apojacsleam喜欢数组。
他现在有一个n个元素的数组a,而他要对a[L]-a[R]进行M次操作:
操作一:将a[L]-a[R]内的元素都加上P
操作二:将a[L]-a[R]内的元素都减去P
最后询问a[l]-a[r]内的元素之和?
请认真看题干及输入描述。
输入描述:
输入共M+3行:
第一行两个数,n,M,意义如“题目描述”
第二行n个数,描述数组。
第3-M+2行,共M行,每行四个数,q,L,R,P,若q为1则表示执行操作2,否则为执行操作1
第4行,两个正整数l,r
输出描述:
一个正整数,为a[l]-a[r]内的元素之和
示例1
输入
10 5
1 2 3 4 5 6 7 8 9 10
1 1 5 5
1 2 3 6
0 2 5 5
0 2 5 8
1 4 9 6
2 7
输出
23
说明
1 ≤ n,M ≤ 1,000,000,所有输入数据都在int范围内。
| 思路:差分标记+前缀和 |
#include<iostream>
#include<cstring>
#include<stack>
#include<queue>
#include<cmath>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const int MAXN = 1e6 + 50;
const int MOD = 1e9 + 7;
const double eps = 1e-9;
const int INF=0x3f3f3f3f;
#define PI acos(-1)
#define IO ios::sync_with_stdio(false);
#define mem(a,b) memset(a,b,sizeof(a))
#define rep(i,x) for(int i=0;i<x;++i)
#define UP(i,x,y) for(int i=x;i<=y;i++)
#define DOWN(i,x,y) for(int i=x;i>=y;i--)
inline int in() {
char ch = getchar();
int f = 1, x = 0;
while (ch < '0' || ch > '9') {
if (ch == '-')
f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
x = (x << 1) + (x << 3) + ch - '0', ch = getchar();
return f * x;
}
LL sum[MAXN];int a[MAXN];
int main()
{
int N,M,q,L,R,P;
LL res = 0;
N=in();M=in();
mem(a,0);
sum[0] = 0;
UP(i,1,N){
sum[i]=in();
}
rep(i,M){
q=in();L=in();R=in();P=in();
if(q == 1){
a[L] -= P; a[R+1] += P;
}
else{
a[L] += P; a[R+1] -= P;
}
}
UP(i,1,N){
a[i] += a[i-1];
sum[i] += sum[i-1] + a[i];
}
L=in();R=in();
printf("%lld\n",sum[R] - sum[L-1]);
return 0;
}
本文介绍了一个区间操作问题的解决方法,通过差分标记与前缀和技巧,实现了对数组指定区间内元素的加减操作,并快速计算指定区间元素之和。
1225

被折叠的 条评论
为什么被折叠?



