bzoj2748:[HAOI2012]音量调节
传送门
简单背包,本来sb了,写的一维数组,后来发现会影响后面的,改成二维就好了
wa的代码给出来:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
void read(int &x) {
char ch; bool ok;
for(ok=0,ch=getchar(); !isdigit(ch); ch=getchar()) if(ch=='-') ok=1;
for(x=0; isdigit(ch); x=x*10+ch-'0',ch=getchar()); if(ok) x=-x;
}
#define rg register
const int maxn=51;
int n,bg,mx,c[maxn],f[1010],ans=-1;
int main()
{
read(n),read(bg),read(mx);
for(rg int i=1;i<=n;i++)read(c[i]);
memset(f,-1,sizeof f);f[bg]=0;
for(rg int i=1;i<=n;i++)
for(rg int j=0;j<=mx;j++)
if(f[j]==i-1)
{
if(j+c[i]<=mx)f[j+c[i]]=i;
if(j-c[i]>=0)f[j-c[i]]=i;
}
for(rg int i=0;i<=mx;i++)if(f[i]==n)ans=max(ans,i);
printf("%d\n",ans);
}
下面是AC代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
void read(int &x) {
char ch; bool ok;
for(ok=0,ch=getchar(); !isdigit(ch); ch=getchar()) if(ch=='-') ok=1;
for(x=0; isdigit(ch); x=x*10+ch-'0',ch=getchar()); if(ok) x=-x;
}
#define rg register
const int maxn=51;
int n,bg,mx,c[maxn],f[51][1010],ans=-1;
int main()
{
read(n),read(bg),read(mx);
for(rg int i=1;i<=n;i++)read(c[i]);
f[0][bg]=1;
for(rg int i=1;i<=n;i++)
for(rg int j=0;j<=mx;j++)
if(f[i-1][j])
{
if(j+c[i]<=mx)f[i][j+c[i]]=i+1;
if(j-c[i]>=0)f[i][j-c[i]]=i+1;
}
for(rg int i=0;i<=mx;i++)
if(f[n][i]==n+1)ans=max(ans,i);
printf("%d\n",ans);
}