题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1881
思路:看到这道题时根本没一点思路,没想到是01背包,挺好的一题,欢乐度看成是价值,持续时间看成是体积,发起人离开时间看成是容量,容量只能是从小到大进行DP,所以要对结构体排一下序,在结构体内写排序函数还是头一次见,练习一下,看了别人的代码A的,有很多地方不了解
AC代码:
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <queue> #include <stack> #include <map> #include <cstring> #include <climits> #include <cmath> #include <cctype> const int inf = 0x3f3f3f3f;//1061109567 typedef long long LL; #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 using namespace std; int dp[10010]; struct node { int h,l,t; friend bool operator < (node a,node b) { return a.t < b.t; } } a[35]; int main() { int n; while(scanf("%d",&n)) { if(n < 0) break; memset(dp,0,sizeof(dp)); for(int i=1; i<=n; i++) scanf("%d%d%d",&a[i].h,&a[i].l,&a[i].t); sort(a+1,a+n+1); int ans = 0; for(int i=1; i<=n; i++) { for(int j=a[i].t; j >=a[i].l; j--) { dp[j] = max(dp[j],dp[j-a[i].l]+a[i].h); ans = max(ans,dp[j]); } } printf("%d\n",ans); } return 0; }
错误代码:
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <queue> #include <stack> #include <map> #include <cstring> #include <climits> #include <cmath> #include <cctype> const int inf = 0x3f3f3f3f;//1061109567 typedef long long LL; #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 using namespace std; int dp[10010]; struct node { int h,l,t; friend bool operator < (node a,node b) { return a.t < b.t; } } a[35]; int main() { int n; while(scanf("%d",&n)) { if(n < 0) break; memset(dp,0,sizeof(dp)); for(int i=1; i<=n; i++) scanf("%d%d%d",&a[i].h,&a[i].l,&a[i].t); sort(a+1,a+n+1); for(int i=1; i<=n; i++) { for(int j=a[i].t; j >=a[i].l; j--) { dp[j] = max(dp[j],dp[j-a[i].l]+a[i].h); } } printf("%d\n",dp[a[n].t]); } return 0; }