区间动规经典(水题)大合集

数字三角形

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define MAXN 100 
using namespace std; 
int n,dp[MAXN+10][MAXN+10],tri[MAXN+10][MAXN+10]; 
void init(){ 
    cin >> n; 
    for (int i = 1; i <= n; i++) 
        for (int j = 1; j <= i ;j++) scanf("%d",&tri[i][j]); 
    memset(dp,0,sizeof dp); 
    for (int i = 1; i <= n; i++) dp[n][i] = tri[n][i]; 
} 
void DP(){ 
    for (int i = n-1; i >= 1; i--) 
        for (int j = 1; j <= i; j++) 
    { 
        int max = tri[i][j] + dp[i+1][j]; 
        if (dp[i+1][j+1] + tri[i][j] > max) max = dp[i+1][j+1] + tri[i][j]; 
        dp[i][j] = max; 
    } 
    cout << dp[1][1] ; 
} 
int main(){ 
    init(); 
    DP(); 
    return 0; 
} 

最长公共子序列

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define MAXN 200 
using namespace std; 
int n,dp[MAXN+10][MAXN+10]; 
char X[MAXN+10],Y[MAXN+10]; 
void init(){ 
    cin >> X; 
    cin >> Y; 
    memset(dp,0,sizeof dp); 
} 
  
int lcs(int m, int n){ 
    for (int i = 1; i <= m; i++) 
        for (int j = 1; j <= n; j++) 
    { 
            if (X[i-1] == Y[j-1]) dp[i][j] = dp[i-1][j-1] + 1; 
            else dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 
    } 
   return dp[m][n]; 
} 
int main(){ 
    init(); 
    cout << lcs(strlen(X),strlen(Y)); 
    return 0; 
} 

采药(背包)

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define MAXN 1000 
using namespace std; 
int T,M; 
int v[MAXN+10],w[MAXN+10],dp[MAXN+10][MAXN+10]; 
void init(){ 
    cin >> T >> M ; 
    for (int i = 1; i <= M; i++) scanf("%d%d",&v[i],&w[i]); 
} 
int f(int T, int n){ 
    for (int i = 0; i <= T; i++) dp[i][0] = 0; 
    for (int i = 1; i <= n; i++) 
        for (int j = 0; j<= T; j++) 
    { 
        dp[j][i] = dp[j][i-1]; 
        if (j >= v[i] && dp[j-v[i]][i-1] + w[i] > dp[j][i]) 
            dp[j][i] = dp[j-v[i]][i-1] + w[i]; 
    } 
    return dp[T][n]; 
} 
int main(){ 
    init(); 
    cout << f(T,M); 
    return 0; 
} 



你可能感兴趣的:(区间动规经典(水题)大合集)