loj10151. 「一本通 5.1 练习 2」分离与合体

思路:
  注意初始化dp[i][i]=0,输出顺序时层序遍历。

#include<cstdio>
#include<iostream>
#include<string>
#include<queue>
using namespace std;
const int maxn = 310;
void qread(int &x){
    x = 0;
    register int ch = getchar();
    if(ch < '0' || ch > '9')    ch = getchar();
    while(ch >= '0' && ch <= '9')    x = 10 * x + ch - 48, ch = getchar();
}
int data[maxn];
int n;
int dp[maxn][maxn];
int sum[maxn];
int pos[maxn][maxn];
queue<pair<int, int> > qu;
void show(int l, int r){
    if(l == r)
        return ;
    cout << pos[l][r] << " ";
    qu.push(make_pair(l, pos[l][r]));
    qu.push(make_pair(pos[l][r] + 1, r));
    while(!qu.empty()){
        int a = qu.front().first, b = qu.front().second;
        qu.pop();
        show(a, b);
    }
}
int main(void){
    qread(n);
    for(int i = 1; i<=n; ++i){
        qread(data[i]);
        dp[i][i] = 0;
        sum[i] = sum[i-1] + data[i];
    }
    for(int L = 1; L < n; ++L)
        for(int i = 1; i + L <= n; ++i){
            int j = i + L;
            dp[i][j] = 0;
            for(int k = i; k < j; ++k){
                int t = dp[i][k] + dp[k + 1][j] + (data[i] + data[j]) * data[k];
                if(t > dp[i][j]){
                    dp[i][j] = t;
                    pos[i][j] = k;
                }
            }
        }
    printf("%d\n", dp[1][n]);
    show(1, n);            
}

猜你喜欢

转载自www.cnblogs.com/junk-yao-blog/p/9488826.html