HDU 46DP (7 01背包问题 8 最长上升子序列O(n*n))

题目:http://acm.hdu.edu.cn/showproblem.php?pid=2602
模板题

#include<bits/stdc++.h>
#define INF 1e18
#define inf 1e9
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define IOS ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std ;
typedef long long ll;
typedef unsigned long long ull;
const int _max = 1050;
struct node{
    int v,p;
}a[_max];
ll dp[_max];
int main(){
    IOS;
    int t,n,v;
    cin>>t;
    while(t--){
        cin>>n>>v;
        for(int i = 1 ; i <= n ; i++)
            cin>>a[i].p;
        for(int i = 1 ; i <= n ; i++)
            cin>>a[i].v;
        memset(dp,0,sizeof(dp));
        for(int i = 1 ; i <= n ; i++){
            int pi = a[i].p;
            int vi = a[i].v;
            for(int j = v ; j >= vi ; j--){
                dp[j] = max(dp[j],dp[j-vi]+pi);
            }
        }
        cout<<dp[v]<<endl;  
    }
    return 0;
}

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1087

这题不能用O(n*logn)的算法。因为最长不等于最大比如1 9 2 3。
所以n*n的方法最好了。
然后dp内存的不是个数是和就行了。

#include<bits/stdc++.h>
#define INF 1e18
#define inf 1e9
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define IOS ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std ;
typedef long long ll;
typedef unsigned long long ull;
const int _max = 1050;
int dp[_max],a[_max];
int main(){
    IOS;
    int n,val;
    while(cin>>n){
        if(!n) break;
        for(int i = 1 ; i <= n ; i++){
            cin>>a[i];
            dp[i] = a[i];
        }
        int res = 0;
        for(int i = 2 ; i <= n ; i++){
            for(int j = 1 ; j <= i ; j++){
                if(a[i] > a[j]){
                    dp[i] = max(dp[i],dp[j]+a[i]);
                }       
            }
            res = max(res,dp[i]);
        }       
        cout<<res<<endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38987374/article/details/79616611