两题都是hihocoder上的。打算用一个礼拜刷掉hihocoder上的DP。
01背包问题:http://hihocoder.com/problemset/problem/1038
#include<bits/stdc++.h>
#define INF 1e18
#define inf 1e9
#define min(a,b) a<b?a:b
#define max(a,b) a>b?a:b
#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 ll mod = 1000000007;
const ll _max = 1e5+50;
int dp[_max];
int main(){
int n,m;
while(cin>>n>>m){
int v,p;
memset(dp,0,sizeof(dp));
for(int i = 1 ; i <= n ; i++){
cin>>v>>p;
for(int j = m ; j >= v ; j--)
dp[j] = max(dp[j-v]+p,dp[j]);
}
cout<<dp[m]<<endl;
}
return 0;
}
完全背包问题:http://hihocoder.com/problemset/problem/1043
#include<bits/stdc++.h>
#define INF 1e18
#define inf 1e9
#define min(a,b) a<b?a:b
#define max(a,b) a>b?a:b
#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 ll mod = 1000000007;
const ll _max = 1e5+50;
int dp[_max];
int main(){
int n,m;
while(cin>>n>>m){
int v,p;
memset(dp,0,sizeof(dp));
for(int i = 1 ; i <= n ; i++){
cin>>v>>p;
for(int j = v ; j <= m ; j++)
dp[j] = max(dp[j-v]+p,dp[j]);
}
cout<<dp[m]<<endl;
}
return 0;
}