标签归档:区间dp

POJ – 3186 Treats for the Cows

题目链接

f[i][j]:只剩第i个到第j个时,将其取完获得的最大价值.

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
const int INF = 1e9;

int f[2005][2005];
int a[2005];
int main() {
  // freopen("in.txt","r",stdin);
  // freopen("out.txt","w",stdout);
  int n;
  cin>>n;
  for(int i=1;i<=n;++i){
    cin>>a[i];
    f[i][i]=n*a[i];
  }
  for(int i=1;i<n;++i){
      for(int l=1;l+i<=n;++l){
        int r=l+i;
        f[l][r]=max(f[l+1][r]+(n-i)*a[l],f[l][r-1]+(n-i)*a[r]);
      }
  }
  cout<<f[1][n]<<endl;
  return 0;
}

洛谷P1880 [NOI1995]石子合并

洛谷P1880 石子合并

区间dp模板题.
注意石子是环形放置的.

#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#define maxn 0x3f3f3f3f
using namespace std;

int dp1[205][205];
int dp2[205][205];
int a[205];
int s[205];
int main(){
  int n;
  cin>>n;
  for(int i=1;i<=n;++i){
    cin>>a[i];
    a[i+n]=a[i];
  }
  for(int i=1;i<=n+n;++i){
    s[i]=s[i-1]+a[i];
  }
  for(int len=2;len<=n;++len){
     for(int i=1;i<=n+n+1-len;++i){
       int j=i+len;
       dp1[i][j]=maxn;
       for(int k=i+1;k<j;++k){
         dp1[i][j]=min(dp1[i][j],dp1[i][k]+dp1[k][j]+s[j-1]-s[i-1]);
         dp2[i][j]=max(dp2[i][j],dp2[i][k]+dp2[k][j]+s[j-1]-s[i-1]);
       }
     }
  }
  int ans1=maxn,ans2=0;
  for(int i=1;i<=n;++i){
    ans1=min(dp1[i][i+n],ans1);
    ans2=max(dp2[i][i+n],ans2);
  }
  cout<<ans1<<endl;
  cout<<ans2<<endl;
  return 0;
}