UVA - 10003 Cutting Sticks(动态规划)

#include<iostream>
#include<cstring>
using namespace std;

const int maxn = 50 + 3;
int l, n;
int c[maxn];
int dp[maxn][maxn];
int vis[maxn][maxn];

int solve2(int i, int j)
{
    if(i == j - 1) return 0;
    if(vis[i][j]) return dp[i][j];
    vis[i][j] = 1;
    int& ans = dp[i][j];
    ans = -1;
    for(int k = i + 1; k < j; k++){
        int v = solve2(i, k) + solve2(k, j) + c[j] - c[i];
        if(ans == -1 || v < ans) ans = v;
    }
    return ans;
}

//d(i, j) = min{d(i, k) + d(k, j)} + c[j] - c[i]
int solve()
{
    for(int i = n; i >= 0; i--){
        for(int j = i + 2; j <= n + 1; j++){
            dp[i][j] = 100000;
            for(int k = i + 1; k < j; k++)
                dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]);
            dp[i][j] += c[j] - c[i];
        }
    }
//    for(int i = 0; i <= n + 1; i++){
//        for(int j = 0; j <= n + 1; j++)
//            cout << dp[i][j] << ' ';
//        cout << endl;
//    }
    return dp[0][n+1];
}

int main()
{
    while(cin >> l && l){
        cin >> n;
        c[0] = 0, c[n+1] = l;
        for(int i = 1; i <= n; i++)
            cin >> c[i];
        memset(dp, 0, sizeof(dp));
        memset(vis, 0, sizeof(vis));
        cout << "The minimum cutting is " << solve() << endl;
        //cout << "The minimum cutting is " << solve2(0, n + 1) << endl;
    }
    return 0;
}

  

posted on 2019-03-21 21:10  nbsanshi  阅读(111)  评论(0编辑  收藏  举报

导航