AcWing100 增減序列 (差分)
阿新 • • 發佈:2020-11-01
題目連結:https://www.acwing.com/problem/content/102/
求出\(a[i]\)的差分數列\(b[i]\),題目的目的是使\(b_2,\ldots,b_n\)都變為\(0\),
令 \(p,q\) 分別為\(\{b_i\}\)中正數和負數之和的絕對值,
優先在\(b_2,\ldots,b_n\)中選一對正負數操作肯定是最優的,
之後再分別與\(b_1或b_n\)配對操作
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<cmath> #include<stack> #include<queue> using namespace std; typedef long long ll; const int maxn = 100010; int n; int a[maxn], b[maxn]; ll pos,neg; ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; } int main(){ n = read(); pos = 0, neg = 0; for(int i=1;i<=n;++i){ a[i] = read(); b[i] = a[i] - a[i-1]; } for(int i=2;i<=n;++i){ if(b[i] < 0) neg += b[i]; if(b[i] > 0) pos += b[i]; } neg = -1ll * neg; printf("%lld\n%lld\n",max(pos,neg),abs(neg - pos) + 1); return 0; }