東華大學2020年程序設計競賽(同步賽)G.Gaming with Mia

東華大學2020年程序設計競賽(同步賽)G.Gaming with Mia

題目鏈接

題目描述

Mia is learning data structures, this semester. After her boyfriend, John, has given so many problems to her, this time, Mia gives John an interesting problem, or rather, an intellectual game.

In this problem, you are given an integer sequence a1, a2, …, an (-1 ≤ ai ≤ 1, 1 ≤ i ≤ n). You are going to determine n - 1 operators op1, op2, …, opn - 1 (opi is either ‘+’ or ‘*’, 1 ≤ i ≤ n - 1) so that the result of the expression S = a1 op1 a2 op2 a3 op3 … opn - 2 an - 1 opn - 1 an is maximized.

Mia is only interested in the maximum result S, but John is unable to tell. Now, John has turned to you for help!

Explanations for the Sample Input and Output

For the first test case, there is only one integer, so we just need to output it: S = 1.

For the second test case, S = 1 + 1 + 1 + 0 = 3.

For the third test case, S = (-1) * (-1) + 0 = 1.

輸入描述:

The first line is an integer T (1 ≤ T ≤ 120), indicates that there are T-group data.

For each test case, the first line contains one integer n (1 ≤ n ≤ 100,000).

The second line contains n integers a1, a2, …, an (-1 ≤ ai ≤ 1, 1 ≤ i ≤ n).

There are no more than 10 test cases with n > 1,000.

輸出描述:

For each test case, output one integer which is the maximum result S.

示例1

輸入

3
1

1
4
1 1 1 0
3
-1 -1 0

輸出

1
3
1

典型的DP,因爲操作符只有 *++ 兩種可能,所以我們可以把結果表達式當作幾個式相加,每個式子是一連串的乘積,所以對每個位置 ii,我們可以用下面的狀態轉移方程:
dp[i]=a[i]+dp[i1]dp[i]=a[i]+dp[i-1]
而對每個 dp[i]dp[i],我們可以通過計算它到前面位置 jj 乘積的最優解來得到最大值:
k=a[ij1]a[i]k=a[i-j-1]*\cdots *a[i]
dp[i]=max(dp[i],dp[ij1]+k)dp[i]=max(dp[i],dp[i-j-1]+k)
AC代碼如下:

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=1e5+5;
int a[N],dp[N];
main(){
    int t,n;
    cin>>t;
    while(t--){
        cin>>n;
        for(int i=0;i<n;i++) cin>>a[i];
        int ans=0;
        dp[0]=a[0];
        for(int i=1;i<n;i++){
            dp[i]=dp[i-1]+a[i];
            int k=a[i];
            for(int j=1;j<=i&&j<=3;j++){
                k*=a[i-j];
                dp[i]=max(dp[i],dp[i-j-1]+k);
            }
        }
        cout<<dp[n-1]<<endl;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章