Daily check-in day 10 - Difference practice

The topics are as follows:

Given a sequence a1, a2,...,an of length n, you can select an interval [l, r] each time so that the numbers with subscripts in this interval will all increase or decrease by one.

Find the minimum number of operations required to make all the numbers in the sequence the same, and find out how many possible types of final sequence are possible under the premise of ensuring the minimum number of operations.

Input format

The first line enters the positive integer n.

In the next n lines, each line enters an integer, and the integer in line i+1 represents ai.

Output format

The first line prints the minimum number of operations.

The second line outputs how many possible outcomes can be obtained.

data range

0<n≤10^5,
0≤ai<2147483648

Input example:

4
1
1
2
2

Output sample:

1
2

 code show as below:
 

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

using namespace std;

const int N = 100010;

typedef long long LL;

int n;
int a[N], b[N];

int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i ++ ) scanf("%d", &a[i]);
    for (int i = 1; i <= n; i ++ ) b[i] = a[i] - a[i - 1];

    LL p = 0, q = 0;
    for (int i = 2; i <= n; i ++ )
        if (b[i] > 0) p += b[i];
        else q -= b[i];

    cout << max(p, q) << endl;
    cout << abs(p - q) + 1 << endl;

    return 0;
}

Idea: The interval increases and decreases, and the difference is obviously examined. Therefore, first find the difference array b[i]. According to the meaning of the question, it can be inferred that only when the difference array is all 0 except the first number, the prefix sum of each bit value obtained To be equal, use variables p and q to record the sum of positive numbers and the sum of negative numbers respectively, and take the maximum value, which is the minimum number of operations required. p - q means that p requires more operands than q. Each operation can be addition or subtraction. That is, how many possibilities there are. Adding 1 indicates how many possibilities there are.

Guess you like

Origin blog.csdn.net/weixin_72758935/article/details/131838404