題目鏈接:
https://vjudge.net/problem/UVA-12563
題意:
題解:
01揹包
一直想二維,但是對於第i首,能不能唱只和時間有關,和前i-1首最多唱了多少沒有關係,不能從dp[i-1]轉移
唱完了一首歌,以這首歌的結束時間判斷是否到了下一首該唱的時間
dp[j]:=以j爲結束時間,最多唱了多少首,注意j一定要倒着枚舉,否則就被當前這首歌覆蓋了,就是這首歌唱了好幾遍【完全揹包】
代碼:
正解:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;
int n,t,a[55];
int dp[180*50+700];
int main(){
int T = read();
int cas = 0;
while(T--){
n = read(), t = read();
for(int i=1; i<=n; i++)
a[i] = read();
int V = min(t,180*n);
memset(dp,-1,sizeof(dp));
dp[0] = 0;
for(int i=1; i<=n; i++)
for(int j=V; j>=a[i]; j--)
if(dp[j-a[i]] >= 0)
dp[j] = max(dp[j],dp[j-a[i]]+1);
int ans1 = 0, ans2;
for(int i=0; i<V; i++){
if(dp[i] >= ans1){
ans1 = dp[i];
ans2 = i;
}
}
printf("Case %d: %d %d\n",++cas,ans1+1,ans2+678);
}
return 0;
}
二維WA的
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;
int n,t,a[55];
int dp[55][180*50+700];
int main(){
int T = read();
int cas = 0;
while(T--){
n = read(), t = read();
for(int i=1; i<=n; i++)
a[i] = read();
int V = min(t,180*n);
memset(dp,0,sizeof(dp));
dp[0][0] = 0;
for(int i=1; i<=n; i++)
for(int j=a[i]; j<V; j++){
dp[i][j] = max(dp[i-1][j],dp[i-1][j-a[i]]+1);
}
int ans1 = 0, ans2;
for(int i=0; i<V; i++){
if(dp[n][i] > ans1){
// cout << ans1 << " " << i << " " << dp[n][i] << endl;
ans1 = dp[n][i];
ans2 = i;
}
}
printf("Case %d: %d %d\n",++cas,ans1+1,ans2+678);
}
return 0;
}