标签:style class blog c code java
/* * @author Panoss */ #include<iostream> #include<cstdio> #include<cstring> #include<string> #include<algorithm> #include<vector> #include<ctime> #include<stack> #include<queue> #include<list> using namespace std; #define DBG 1 #define fori(i,a,b) for(int i = (a); i < (b); i++) #define forie(i,a,b) for(int i = (a); i <= (b); i++) #define ford(i,a,b) for(int i = (a); i > (b); i--) #define forde(i,a,b) for(int i = (a); i >= (b); i--) #define forls(i,a,b,n) for(int i = (a); i != (b); i = n[i]) #define mset(a,v) memset(a, v, sizeof(a)) #define mcpy(a,b) memcpy(a, b, sizeof(a)) #define dout DBG && cerr << __LINE__ << " >>| " #define checkv(x) dout << #x"=" << (x) << " | "<<endl #define checka(array,a,b) if(DBG) { \ dout<<#array"[] | " << endl; forie(i,a,b) cerr <<"["<<i<<"]="<<array[i]<<" |"<<((i-(a)+1)%5?" ":"\n"); if(((b)-(a)+1)%5) cerr<<endl; } #define redata(T, x) T x; cin >> x #define MIN_LD -2147483648 #define MAX_LD 2147483647 #define MIN_LLD -9223372036854775808 #define MAX_LLD 9223372036854775807 #define MAX_INF 18446744073709551615 inline int reint() { int d; scanf("%d",&d); return d; } inline long relong() { long l; scanf("%ld",&l); return l; } inline char rechar() { scanf(" "); return getchar(); } inline double redouble() { double d; scanf("%lf", &d); return d; } inline string restring() { string s; cin>>s; return s; } const int N = 1024; int w[N],p[N]; int f[N][N]; /* f[i][j]代表前i件物品容量为j的最大值 状态转移方程f[i][j] = max(f[i-1][j-w[i]]+p[i],f[i-1][j]) */ void DP(int n,int c) ///从n件物品选出物品,使容量最大值,不超过c { mset(f,0); forie(i,1,n) ///从第一件物品开始,自低向上 { forie(j,0,c) ///枚举背包容量,自低向上 { if(j>=w[i]) { f[i][j] = max(f[i-1][j-w[i]]+p[i],f[i-1][j]); } else f[i][j] = f[i-1][j]; } } } int main() { int n,c; while(cin>>n>>c,(n+c)) { forie(i,1,n) cin>>w[i]; forie(i,1,n) cin>>p[i]; DP(n,c); cout<<f[n][c]<<endl; } }
一维DP解法:
const int N = 1024; int w[N],p[N]; int d[N]; /// d[i]表示体积为i的最大值 /// 状态转移方程d[i] = max(d[i-w[i]]+p[i],d[i]) void DP(int n,int c) ///从n件物品选出物品,使容量最大值,不超过c { mset(d,0); forie(i,1,n) ///从第一件物品开始,自低向上 { forde(j,c,w[i]) ///枚举背包容量,注意方向,从c至w[i] { if(j>=w[i]) { d[j] = max(d[j-w[i]]+p[i],d[j]); } } } } int main() { int n,c; while(cin>>n>>c,(n+c)) { forie(i,1,n) cin>>w[i]; forie(i,1,n) cin>>p[i]; DP(n,c); cout<<d[c]<<endl; } }
标签:style class blog c code java
原文地址:http://www.cnblogs.com/Panoss/p/3741967.html