天天看點

dp - HNU 13404 The ImpThe Imp  Problem's Link:  http://acm.hnu.cn/online/?action=problem&type=show&id=13404&courseid=0

Mean: 

n個物品,每個物品價值為v,價格為c,你隻可以帶一個物品離開。

有一個精靈,它可以施法讓你購買後的物品價值變為0(未離開商店之前),精靈最多施k次法術。

你的目的是讓自己獲得最大收益,而小鬼的目的正好相反。

如果你和精靈都采用最優政策,最後你可以盈利多少?

analyse:

第一感覺是三維dp,然而三維肯定會逾時超記憶體。

然後就是想怎樣壓縮狀态。。。

想了想其實兩維就夠了,為什麼呢?因為對于第i件物品,如果我不選,那麼它這次施不施法是沒有影響的。

dp[i][j]:判斷到第i個物品,精靈施了j次魔法,我還能獲得的最大收益。

狀态轉移方程:dp[i][j]=max(dp[i-1][j],min(dp[i-1][j-1]-c,v-c))

僞代碼:

for_each i

{

   if(select i)

   {

       for_each j

       {

           if(magic j time)

           {

               max(before i) - cost;

           }

           else

               value-cost;

       }

   }

   else

       max(before i);

}

Time complexity: O(N*K)

Source code: 

/*

* this code is made by crazyacking

* Verdict: Accepted

* Submission Date: 2015-08-15-12.09

* Time: 0MS

* Memory: 137KB

*/

#include <queue>

#include <cstdio>

#include <set>

#include <string>

#include <stack>

#include <cmath>

#include <climits>

#include <map>

#include <cstdlib>

#include <iostream>

#include <vector>

#include <algorithm>

#include <cstring>

#define  LL __int64

#define  ULL unsigned long long

using namespace std;

const LL MAXN=200010;

struct node

     LL v,c;

     bool operator <(const node&a) const

     {

           return v>a.v;

     }

} a[MAXN];

LL dp[MAXN][10];

int main()

     ios_base::sync_with_stdio(false);

     cin.tie(0);

     LL Cas;

     scanf("%I64d",&Cas);

     while(Cas--)

           LL n,k;

           scanf("%I64d %I64d",&n,&k);

           for(LL i=1; i<=n; ++i)

                 scanf("%I64d %I64d",&a[i].v,&a[i].c);

           sort(a+1,a+n+1);

           LL ans=0,val;

           memset(dp,0,sizeof dp);

                 val=a[i].v-a[i].c;

                 dp[i][0]=max(dp[i-1][0],val);

                 for(LL j=1; j<=k; ++j)

                 {

                       dp[i][j]=max(dp[i-1][j],min(dp[i-1][j-1]-a[i].c,val));

                 }

                 ans=max(ans,dp[i][k]);

           printf("%I64d\n",ans);

     return 0;

繼續閱讀