IncDec Sequence (差分)

Topics address

This question can be used to detect whether you learned the difference, or you can be more thorough understanding of the difference

We \ (cf [] \) (differential) arrays come up, you can find this question is the time to be in \ (cf [] \) select two numbers, a + 1, a -1, How minimum number of steps \ (cf [2] -cf [ n] \) in all of the number becomes 0

Considering \ (cf [] \) arrays have negative numbers are also positive, we set \ (p \) is so negative sum \ (q \) is so positive sum, we affirm the priority of positive and negative offset, set after the positive and negative offset there \ (| pq | \) , which we make and \ (cf [1] \) or \ (cf [n + 1] \) elimination, so the shortest number of steps is \ (\ text max} {(P, Q) \) , is different from the last value \ (| pq | +1 \)

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e5+7;
int n,p,q;
int a[N],cf[N];
signed main()
{
    scanf("%lld",&n);
    for(int i=1;i<=n;++i) {
        scanf("%lld",&a[i]);
        cf[i] = a[i] - a[i-1];
    }
    for(int i=2;i<=n;++i) {
        if(cf[i] > 0) p += cf[i];
        if(cf[i] < 0) q += -cf[i];
    }
    printf("%lld\n%lld\n",max(p,q),abs(p-q)+1);
    return 0;
}

Guess you like

Origin www.cnblogs.com/BaseAI/p/11417404.html