哇,本以为逃出了dp问题,结果转身又掉了进去。我的脑子哇。这次是0 1背包问题,感觉和我之前遇到的不太一样,还没有切实的编过程序。来看看哇。我一开始的思路是找单位体积价值最大的,进行填充,发现WA了,想了老一会,哦~~~原来是有可能一个单位体积价值最大的,导致空间剩余,使其在空间上变小。如果是可以分割的话,估计就正确了。上一波错的代码:
#include <iostream>
#include <iomanip>
#include<queue>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<iomanip>
#include<string.h>
#include<sstream>
#include<string>
#include<queue>
#define MAX 5842
//¶¨Ò庯Êý¶Î
#define repf(i,a,b) for(int i =(a);i<(b);i++)
#define repfe(i,a,b) for(int i =(a);i<=(b);i++)
using namespace std;
struct thing{
public:
double value ;
double v ;
};
thing things[1001];
bool cmp(thing a ,thing b )
{
return a.value/a.v>b.value/b.v;
}
int main() {
double num ;
int res ,n,v;
cin >> num ;
while(num--)
{
cin>>n>>v;
repf(i,0,n)
{
cin>>things[i].value;
}
repf(i,0,n)
{
cin>>things[i].v;
}
sort(things,things+n,cmp);
res = 0 ;
repf(i,0,n)
{
if(v>=things[i].v)
{
v-=things[i].v;
res +=things[i].value;
}
}
cout << res <<endl;
}
}
正确的代码。emmm要是没看懂上边的,估计多看两遍代码也就懂了,哎,算法哇
#include <iostream>
#include <iomanip>
#include<queue>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<iomanip>
#include<string.h>
#include<sstream>
#include<string>
#include<queue>
#define MAX 5842
//¶¨Ò庯Êý¶Î
#define repf(i,a,b) for(int i =(a);i<(b);i++)
#define repfe(i,a,b) for(int i =(a);i<=(b);i++)
using namespace std;
struct thing{
public:
int value ;
int v ;
};
thing things[1111];
int dp[1111];
int main() {
int num, n,v;
cin >> num ;
while(num--)
{
scanf("%d %d", &n,&v);
memset(dp,0,sizeof(dp));
repf(i,0,n)
{
cin>>things[i].value;
}
repf(i,0,n)
{
cin>>things[i].v;
}
repf(i,0,n)
{
for(int j =v ; j>=things[i].v ; j--)
{
dp[j] = max(dp[j],dp[j-things[i].v]+things[i].value);
}
}
printf("%d\n",dp[v] );
}
return 0 ;
}