AcWing100 增减序列 (差分)

时间:2020-11-01 22:16:53   收藏:0   阅读:32

题目链接: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;
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!