A10 差分 二维差分
视频链接:A10 差分 二维差分_哔哩哔哩_bilibili
Luogu P4552 [Poetize6] IncDec Sequence
#include <iostream> #include <cstring> using namespace std; typedef long long LL; const int N=100010; int a[N], b[N]; int main(){ int n; cin>>n; for(int i=1; i<=n; i++) cin>>a[i]; for(int i=1; i<=n; i++) b[i]=a[i]-a[i-1]; LL p=0, q=0; for(int i=2; i<=n; i++) if(b[i]>0) p+=b[i]; else q+=abs(b[i]); cout<<max(p,q)<<'\n'<<abs(p-q)+1; }
#include<cstdio> #include<iostream> using namespace std; int a[1005][1005]; //差分数组 int main(){ int n,m; scanf("%d%d",&n,&m); while(m--){ int x1,y1,x2,y2; scanf("%d%d%d%d",&x1,&y1,&x2,&y2); for(int i=x1; i<=x2; i++){ a[i][y1]++; a[i][y2+1]--; //逐行差分 } } for(int i=1; i<=n; i++){ for(int j=1; j<=n; j++){ a[i][j]+=a[i][j-1]; //逐行还原 printf("%d ",a[i][j]); } puts(""); } }
练习:
Luogu P2879 [USACO07JAN] Tallest Cow S