由于是背包问题,但直接用dp, 不满足dp中的无后效性,所以用排序来改变顺序;
#include <cstdio> #include <cmath> #include <algorithm> #include <iostream> #include <queue> #include <cstdlib> #include <cstring> #define maxn 3005 using namespace std; const int INF = 0x3f3f3f; int dp[10005]; int ans = 0; struct task{ int t,s; double ave; }Node[maxn]; int T,N; int cmp(task a,task b){ if(fabs(a.ave - b.ave) < 1e-5) return a.t > b.t; return a.ave > b.ave; } int main(){ //if(freopen("input.txt","r",stdin)== NULL) {printf("Error\n"); exit(0);} while(scanf("%d%d",&N,&T)==2){ ans = 0; memset(dp,0,sizeof(dp)); for(int i=1;i<=N;i++){ scanf("%d%d",&Node[i].t,&Node[i].s); Node[i].ave = 1.0*Node[i].s/(1.0*Node[i].t); } sort(Node+1,Node+N+1,cmp); for(int i=1;i<=N;i++) for(int t=T;t>=Node[i].t;t--){ if(dp[t] < dp[t - Node[i].t] + (T - t + Node[i].t) *Node[i].s){ dp[t] = dp[t - Node[i].t] + (T - t + Node[i].t) * Node[i].s; } } for(int i=1;i<=T;i++) ans = max(ans,dp[i]); printf("%d\n",ans); } return 0; }