POJ 1160 (區間DP+四邊形最佳化),pojdp

來源:互聯網
上載者:User

POJ 1160 (區間DP+四邊形最佳化),pojdp

這個轉移方程不好想,尤其是一段值的解是中間,不明覺厲。dp[i][j] 用i個郵局,覆蓋前j個村莊的最小值。

還有就是區間dp的平行四邊形最佳化,這個題的轉移方程並不是“區間DP”,所以枚舉狀態要逆著(很花時間),且用一個郵局覆蓋都是從0斷開了相當於沒有斷開。

類比於石子歸併,矩陣鏈乘等標準區間DP,其所需狀態之前就已經獲得,不用反向推算


#include <cstdio>#include <cstring>#include <iostream>using namespace std;const int NN=310;const int INF=0x7fffffff;int n,m;int s[NN],dp[NN][NN],w[NN][NN],p[NN][NN];void get_w()//求在i~j號村莊間建一個郵局的最小距離和{    for (int i=1; i<n; i++)      for (int j=i+1; j<=n; j++)      {          if ((i+j)%2) w[i][j]=s[j]-s[(i+j)/2]*2+s[i-1];          else         w[i][j]=s[j]-s[(i+j)/2]-s[(i+j)/2-1]+s[i-1];      }}void get_dp(){    for (int i=1; i<=n; i++)    {        dp[1][i]=w[1][i];        p[1][i]=0;//注意這裡    }    for (int c=2; c<=m; c++)    {        p[c][n+1]=n;        for (int i=n; i; i--)///這裡倒著寫,p[c][i+1]是取後面值        {            int tmp=INF,k;            for (int j=p[c-1][i]; j<=p[c][i+1]; j++)            {                if (dp[c-1][j]+w[j+1][i]<tmp) tmp=dp[c-1][k=j]+w[j+1][i];            }            dp[c][i]=tmp;            p[c][i]=k;        }    }}int main(){    scanf("%d%d",&n,&m);    s[0]=0;    int x;    for (int i=1; i<=n; i++)    {        scanf("%d",&x);        s[i]=s[i-1]+x;    }    get_w();    get_dp();    printf("%d",dp[m][n]);    return 0;}

//直線取石子問題的平行四邊形最佳化:#include <iostream>#include <string.h>#include <stdio.h>using namespace std;const int INF = 1 << 30;const int N = 1005;int dp[N][N];int p[N][N];int sum[N];int n;int getMinval(){    for(int i=1; i<=n; i++)    {        dp[i][i] = 0;        p[i][i] = i;//這個自己跟自己乘自然是以自己為分割了。    }    for(int len=1; len<n; len++)    {        for(int i=1; i+len<=n; i++)        {            int end = i+len;            int tmp = INF;            int k = 0;            for(int j=p[i][end-1]; j<=p[i+1][end]; j++)            {                if(dp[i][j] + dp[j+1][end] + sum[end] - sum[i-1] < tmp)                {                    tmp = dp[i][j] + dp[j+1][end] + sum[end] - sum[i-1];                    k = j;                }            }            dp[i][end] = tmp;            p[i][end] = k;        }    }    return dp[1][n];}int main(){    while(scanf("%d",&n)!=EOF)    {        sum[0] = 0;        for(int i=1; i<=n; i++)        {            int val;            scanf("%d",&val);            sum[i] = sum[i-1] + val;        }        printf("%d\n",getMinval());    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.