基础DP总结

1.数塔

(1)自顶向下

#include 
using namespace std;
int dp[105][105] = {0};
int main()
{
    std::ios::sync_with_stdio(0);
    int i, j, n, ans;
    cin >> n;
    for(i = 1; i <= n; i++)
    {
        for(j = 1; j <= i; j++)
        {
            cin >> dp[i][j];
            dp[i][j] += max(dp[i - 1][j], dp[i - 1][j - 1]);
        }
    }
    for(i = 1; i <= n; i++)ans = max(ans, dp[n][i]);
    cout << ans << endl;
}

(2)自底向上

#include 
using namespace std;
int dp[105][105] = {0};
int main()
{
    std::ios::sync_with_stdio(0);
    int i, j, n, ans;
    cin >> n;
    for(i = n - 1; i >= 1; i++)
    {
        for(j = 1; j <= i; j++)
        {
            cin >> dp[i][j];
            dp[i][j] += max(dp[i + 1][j], dp[i + 1][j + 1]);
        }
    }
    cout << dp[1][1] << endl;
}

题目:HDU-1176

2.最长上升子序列

#include 
using namespace std;
int a[1005], dp[1005] = {0};
int main()
{
    std::ios::sync_with_stdio(0);
    int n, i, j, ans = -1;
    cin >> n;
    for(i = 1; i <= n; i++)cin >> a[i];
    for(i = 1; i <= n; i++)
    {
        dp[i] = 1;
        for(j = 1; j < i; j++)
        {
            if(a[i] > a[j])dp[i] = max(dp[i], dp[j] + 1);
        }
        ans = max(ans, dp[i]);
    }
    cout << ans << endl;
    return 0;
}

题目:HDU-1087、HDU-1257、HDU-1160、POJ-2533、POJ-3616

3.最长公共子序列

#include 
using namespace std;
char s1[1005], s2[1005];
int dp[1005][1005] = {0};
int main()
{
    std::ios::sync_with_stdio(0);
    int i, j, k, len1, len2;
    cin >> s1 >> s2;
    len1 = strlen(s1);
    len2 = strlen(s2);
    for(i = 1; i <= len1; i++)
    {
        for(j = 1; j <= len2; j++)
        {
            if(s1[i - 1] == s2[j - 1])dp[i][j] = dp[i - 1][j - 1] + 1;
            else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
        }
    }
    cout << dp[len1][len2] << endl;
    return 0;
}

题目:POJ-1458

4.背包

(1)0-1背包:f[i][v]=max{f[i-1][v],f[i-1][v-c[i]]+w[i]}

(2)完全背包:f[i][v]=max{f[i-1][v-k*c[i]]+k*w[i]|0<=k*c[i]<=v}

(3)多重背包:f[i][v]=max{f[i-1][v-k*c[i]]+k*w[i]|0<=k<=n[i]}

 

你可能感兴趣的:(学习笔记)