Luo Yongjun→"Algorithm Contest·Quick 300 Questions" One question per day: "Product" ← Dynamic Programming

[Title source]
http://oj.ecustacm.cn/problem.php?id=1781
http://oj.ecustacm.cn/viewnews.php?id=1023

[Title description]
Give you a sequence of length n , the elements in the sequence only include 1 and -1.
How many consecutive subsequences have a positive product.

【Input format】
Enter the first row as a positive integer n. (n does not exceed 10^6)
The second line contains n integers.

【Output Format】
Output a number to represent the answer.

[Input example]
4
1 1 -1 -1

[Output example]
6

[Algorithm analysis]
● Dynamic programming
The last step: https://blog.csdn.net/hnjzsyjyj/article/details/112797538

This question is "
counting type " problem can be solved by dynamic programming algorithm.
(1) Establish the state
Let the input sequence be a[1]~a[n], according to the last step method, the DP state can be defined as:

f[i][0]: the product ending with a[i] is -1 The number of consecutive subsequences
f[i][1]: the number of consecutive subsequences ending with a[i] whose product is 1.

For example, for the sample {1, 1, -1, -1}, with f[1][1]=1, f[2][1]=2, f[3][1]=0, f[4][1] =3.
(2) State transition equation
If a[i]=1:

f[i][1]=f[i-1][1]+1, add 1 to the number of continuous subsequences whose product is 1
f[i][ 0]=f[i-1][0], the product continues to be -1

if a[i]=-1:
f[i][1]=f[i-1][0]
f[i][0 ]=f[i-1][1]+1

Finally, add up all f[i][1] to get the answer.

【Algorithm code】

#include<bits/stdc++.h>
using namespace std;

const int maxn=1e6+5;
int a[maxn];
long long f[maxn][2];
long long ans;

int main() {
    int n;
    cin>>n;
    for(int i=1; i<=n; i++) cin>>a[i];

    for(int i=1; i<=n; i++) {
        if(a[i]==1) {
            f[i][1]=f[i-1][1]+1;
            f[i][0]=f[i-1][0];
        } else if(a[i]==-1) {
            f[i][1]=f[i-1][0];
            f[i][0]=f[i-1][1]+1;
        }
    }

    for(int i=1; i<=n; i++) ans=ans+f[i][1];
    cout<<ans<<endl;

    return 0;
}


/*
in:
4
1 1 -1 -1

out:
6
*/



[References]
https://blog.csdn.net/weixin_43914593/article/details/131810636
https://blog.csdn.net/hnjzsyjyj/article/details/112797538




 

Guess you like

Origin blog.csdn.net/hnjzsyjyj/article/details/132439574