6.1 线性DP

具有线性“阶段”划分的动态规划算法被称为线性DP。常见的有最长上升子序列(LIS),最长公共子序列(LCS),数字三角形等。

相关练习:

1. Mr. Young's Picture Permutations(POJ2279)

2.LCIS(最长公共上升子序列)

#include<iostream>

using namespace std;

const int N = 3100;

int a[N], b[N];
int f[N][N];
int n;

int main(){
    cin>>n;
    for(int i = 1; i <= n ;++i) cin>>a[i];
    for(int i = 1; i <= n; ++i )cin>>b[i];
    
    for(int i = 1; i <= n; ++i){
        for(int j = 1; j <= n; ++j){
            int& x= f[i][j];
            x = f[i-1][j];
            if(a[i] == b[j]){
                x = max(x, 1);
                for(int k = 1; k < j; ++k){
                    if(b[k] < b[j]) x = max(x, f[i-1][k]+1);
                }
            }
        }
    }
    int ans = 0;
    for(int i = 1; i <= n; ++i)
        ans = max(ans, f[n][i]);
    cout<<ans<<endl;
    return 0;
}

3.Making the Grade(POJ3666)

4.Mobiles Service

5.传纸条

#include<iostream>

using namespace std;

const int N = 60;

int f[N*2][N][N];

int arr[N][N];

int n, m;

int main(){
    cin>>n>>m;
    for(int i = 1; i <= n; ++i){
        for(int j = 1; j <= m; ++j)
            cin>>arr[i][j];
    }
    
    
    for(int i = 2; i <= n + m; ++i){
        for(int l1 = 1; l1 <= n; ++l1){
            for(int l2 = 1; l2 <= n; ++ l2){
                int r1 = i - l1, r2 = i - l2;
                
                if(r1 >= 0 && r1 <= m && r2 >= 0 && r2 <= m){
                    
                        //ll
                    int & l = f[i][l1][l2];
                    
                    l = f[i-1][l1-1][l2-1];
                    
                    //lt
                    l = max(l, f[i-1][l1-1][l2]);
                    
                    //tl
                    l = max(l, f[i-1][l1][l2-1]);
                    
                    //tt
                    l = max(l, f[i-1][l1][l2]);
                    
                    l += arr[l1][r1];
                    if(l1 != l2) l += arr[l2][r2];
                    
                }
            }
        }
    }
    

    cout<<f[n+m][n][n]<<endl;
    return 0;
        
}

6.I-country

7.Cookies

posted @ 2020-01-02 18:28  楓羽  阅读(207)  评论(0编辑  收藏  举报