AcWing100 增减序列 (差分)

题目链接: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
%lld
",max(pos,neg),abs(neg - pos) + 1);
	 
	return 0;
}
原文地址:https://www.cnblogs.com/tuchen/p/13910220.html