HDU3506-Monkey Party(區間DP 石子合併 四邊形不等式優化)

題目鏈接

Problem Description

Far away from our world, there is a banana forest. And many lovely monkeys live there. One day, SDH(Song Da Hou), who is the king of banana forest, decides to hold a big party to celebrate Crazy Bananas Day. But the little monkeys don't know each other, so as the king, SDH must do something.
Now there are n monkeys sitting in a circle, and each monkey has a making friends time. Also, each monkey has two neighbor. SDH wants to introduce them to each other, and the rules are:
1.every time, he can only introduce one monkey and one of this monkey's neighbor.
2.if he introduce A and B, then every monkey A already knows will know every monkey B already knows, and the total time for this introducing is the sum of the making friends time of all the monkeys A and B already knows;
3.each little monkey knows himself;
In order to begin the party and eat bananas as soon as possible, SDH want to know the mininal time he needs on introducing.

Input

There is several test cases. In each case, the first line is n(1 ≤ n ≤ 1000), which is the number of monkeys. The next line contains n positive integers(less than 1000), means the making friends time(in order, the first one and the last one are neighbors). The input is end of file.

Output

For each case, you should print a line giving the mininal time SDH needs on introducing.

Sample Input

8

5 2 4 7 6 1 3 9

Sample Output

105


題意

相當於一堆石子排成一個環,每次操作可以將兩堆石子合併爲一堆,分數爲兩堆石子之和,問最小值

思路

環的問題,可以轉化爲兩個相同的行拼成一塊。

四邊形不等式優化


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;

int x,n,a[2010],dp[2010][2010],s[2010][2010];
int sum[2010];

int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=1;i<=n;i++) {scanf("%d",&a[i]); }
        for(int i=n+1;i<=2*n;i++) {a[i] = a[i-n];}
        for(int i=1;i<=2*n;i++){
            sum[i] = sum[i-1] + a[i];
            dp[i][i] = 0;
            s[i][i] = i;
        }

        for(int l=2;l<=2*n;l++){
            for(int i=1;i<=2*n;i++){
                int j = i+l-1;
                if(j>2*n) continue;
                int mmin = inf;
                for(int k=s[i][j-1];k<=s[i+1][j];k++){
                    int t = dp[i][k]+dp[k+1][j]+sum[j]-sum[i-1];
                    if(t<mmin){
                        mmin = t;
                        s[i][j] = k;
                    }
                }
                dp[i][j] = mmin;//printf("i:%d j:%d dp:%d\n",i,j,mmin);
            }
        }
        int mmin = inf;
        for(int i=1;i<=n;i++){
            if(mmin>dp[i][i+n-1]) mmin = dp[i][i+n-1];
        }
        printf("%d\n",mmin);
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章