Codeforces 366C Dima and Salad

http://codeforces.com/problemset/problem/366/C

题意:在一个冰箱里有n种水果,并且这些水果每一种都有一个美味度和一个卡路里的属性, 小明要从这些水果中选出来一些做一个水果沙拉, 并且要求他的水果沙拉的美味度之和是卡路里和的k倍,问小明是否可以做出这么一个水果沙拉,若不能输出-1,否则输出符合要求的最大的美味值之和。

思路:考虑这样DP:f[i][j]:做到第i个水果,平衡度为j,平衡度的表示:Σa[i]-K*Σb[i],这样就可以dp

f[i][j]=max(f[i-1][j],f[i-1][j-a[i]+K*b[i]])

 1 #include<cstdio>
 2 #include<cmath>
 3 #include<algorithm>
 4 #include<cstring>
 5 #include<iostream>
 6 int f[105][100005],a[1005],b[1005],g[1005][1005];
 7 int n,K;
 8 int read(){
 9     int t=0,f=1;char ch=getchar();
10     while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
11     while ('0'<=ch&&ch<='9'){t=t*10+ch-'0';ch=getchar();}
12     return t*f;
13 }
14 int main(){
15     n=read();K=read();
16     for (int i=1;i<=n;i++) a[i]=read();
17     for (int i=1;i<=n;i++) b[i]=read();
18     for (int i=0;i<=n;i++)
19      for (int j=0;j<=500000;j++)
20       f[i][j]=-99999999;
21     f[0][20000]=0;  int cnt=0;
22     for (int i=1;i<=n;i++){
23         cnt++;
24         for (int j=-10000;j<=10000;j++){
25            f[i][j+20000]=std::max(f[i][j+20000],std::max(f[i-1][j+20000],f[i-1][j-a[i]+K*b[i]+20000]+a[i]));
26         }
27     }
28     int ans=-1;
29     if (f[n][20000]) ans=f[n][20000];
30     printf("%d
",ans);
31     return 0;
32 }
原文地址:https://www.cnblogs.com/qzqzgfy/p/5622922.html