IncDec Sequence (increasing and decreasing sequence) Acwing102-prefix sum, difference

IncDec Sequence (Increase and Decrease Sequence) Acwing102

Problem:
Given a sequence a1, a2,..., an of length n, you can select an interval [l, r] each time, so that all the numbers in this interval are increased by one or all subtracted by one.

Find at least how many operations are required to make all the numbers in the sequence the same, and find out how many kinds of sequence can be finally obtained under the premise of ensuring the minimum number of times.

Input format
Enter a positive integer n in the first line.

In the next n rows, enter an integer in each row, and the integer in the i+1th row represents ai.

Output format The
first line outputs the minimum number of operations.

The second line outputs how many kinds of results can be finally obtained.

Data range
0<n≤10^5,
0≤ai<2147483648
Input example:
4
1
1
2
2
Output example:
1
2

/*
题意:对区间(l , r)中的元素加减一操作使得整个数列为常数列最少需要操作多少次,最终的常数列有多少种

这种需要对区间每个元素操作的方法很快就能想到 前缀和与差分, 这题使用差分序列完成。
差分决策:
只需要将[2 ~ N]中的差分序列全部变为0即可。
选择区间的可能:
1、 2 <= i , j <= N 尽可能的选择一正一负的i ,j保证接近目标
2、 i = 1, 2 <= j <= N 
3、 j = 1, 2 <= i <= N
——2 、3 将i,j配对化为其中一个
4、 i = 1 , j = N 毫无意义

其中假设序列中正整数总和为p、负整数为q。则先采用第一种方案最少需要执行min(p, q)种操作。
剩余| p - q |个未匹配的采用第2、 3种方案化为其中的一个数。所以总操作次数未min(p, q) + |p - q|
一共可以产生|p - q| + 1种数列
*/

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;

typedef long long LL;

const int N = 1e5 + 10;
int a[N];

int main(){
    
    
    int n;
    cin >> n;
    for(int i = 1; i <= n; i++)cin >> a[i];
    for(int i = n; i > 1; i-- ) a[i] -= a[i - 1];//计算差分序列
    
    LL pos = 0, neg = 0;
    for(int i = 2; i <= n; i++){
    
    
        if(a[i] > 0)pos+=a[i];//计算正整数的总和
        else neg -= a[i];//计算负整数的总和
    }
    cout << min(pos, neg) + abs(pos - neg) << endl;
    cout << abs(pos - neg) + 1 << endl;
    
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_45830383/article/details/108686010