前缀和与差分 AcWing 797. 差分
原题链接
算法标签
差分
思路
代码
#include<bits/stdc++.h>
#define int long long
#define rep(i, a, b) for(int i=a;i<b;++i)
#define Rep(i, a, b) for(int i=a;i>b;--i)
using namespace std;
const int N = 100005;
int a[N], b[N];
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
return s*w;
}
void put(int x) {
if(x<0) putchar('-'),x=-x;
if(x>=10) put(x/10);
putchar(x%10^48);
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n=read(), m=read();
rep(i, 1, n+1){
a[i]=read();
b[i]+=a[i];
b[i+1]-=a[i];
}
while(m--){
int l=read(), r=read(), c=read();
b[l]+=c;
b[r+1]-=c;
}
rep(i, 1, n+1){
b[i]+=b[i-1];
}
rep(i, 1, n+1){
printf("%lld ", b[i]);
}
return 0;
}
y总代码
#include <iostream>
using namespace std;
const int N = 100010;
int n, m;
int a[N], b[N];
void insert(int l, int r, int c)
{
b[l] += c;
b[r + 1] -= c;
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i ++ ) scanf("%d", &a[i]);
for (int i = 1; i <= n; i ++ ) insert(i, i, a[i]);
while (m -- )
{
int l, r, c;
scanf("%d%d%d", &l, &r, &c);
insert(l, r, c);
}
for (int i = 1; i <= n; i ++ ) b[i] += b[i - 1];
for (int i = 1; i <= n; i ++ ) printf("%d ", b[i]);
return 0;
}
总结学习
由于插入操作前后重复运用 ,可以封装为函数。
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈