2020 ICPC 線上模擬賽 E題 Eat Walnuts(區間dp)

Authur_gyc發表於2020-11-01

E Eat Walnuts

思路

簡單的區間dp,注意邊界值不能選,i>j部分應初始化為0(而不是INF)

程式碼

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 1e2 + 10;
const int INF = 5e8 + 10;
int a[maxn];
int dp[maxn][maxn];
int power(int x){
    return x * x;
}
int main(){
    int n;
    while(scanf("%d", &n)!=EOF){
        for(int i = 1; i <= n; i++){
            scanf("%d", &a[i]);
        }
        for(int i = 1; i <= n; i++){
            for(int j = i; j <= n; j++){
                dp[i][j] = INF;
            }
        }
        for(int i = 2; i <= n - 1; i++){///區間長度為1
            dp[i][i] = power(a[i - 1] + a[i] + a[i + 1]);
        }
        for(int len = 2; len <= n - 2; len++){///區間長度,開區間,不包括兩個端點
            for(int s = 2; s + len - 1 <= n - 1; s++){
                int e = s + len - 1;
                for(int k = s; k <= e; k++){
                    dp[s][e] = min(dp[s][e], dp[s][k - 1] + dp[k + 1][e] + power(a[s - 1] + a[k] + a[e + 1]));
                }
            }
        }
        printf("%d\n", dp[2][n - 1]);
    }
    return 0;
}

相關文章