【HDU 5887】Herbs Gathering(dfs+时间剪枝)

【HDU 5887】Herbs Gathering(dfs+时间剪枝)

题目大意:
n个物体 每个物品有体积和价值,取V体积问最大价值。

背包,不过数据很大……
然后……先写个暴力的dfs,TLE
然后按性价比排个序,TLE
然后加各种剪枝,TLE

赛后(clock()-st)/CLOCKS_PER_SEC <= 0.02 st为dfs前取的clock()
跑的比谁都快……不想说话。。

代码如下:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define LL long long
#define Pr pair
#define fread(ch) freopen(ch,"r",stdin)
#define fwrite(ch) freopen(ch,"w",stdout)

using namespace std;
const int INF = 0x3f3f3f3f;
const int msz = 10000;
const int mod = 1e9+7;
const double eps = 1e-8;

struct Obj
{
    LL v,w;
    double xjb;
    bool operator < (const struct Obj a)const
    {
        return xjb > a.xjb;
    }
} obj[111];

int n;
LL v,mn;
LL ans;
double c;

void dfs(int pos,LL sum,LL v)
{
    if((clock()-c)/CLOCKS_PER_SEC > 0.02) return;
    ans = max(ans,sum);
    if(sum+obj[pos].xjb*v < ans) return;
    if(v < mn) return;
    if(pos == n) return;

    if(obj[pos].v <= v) dfs(pos+1,sum+obj[pos].w,v-obj[pos].v);
    dfs(pos+1,sum,v);
}

int main()
{
    //fread("");
    //fwrite("");

    while(~scanf("%d%lld",&n,&v))
    {
        mn = 1e9+7;
        for(int i = 0; i < n; ++i)
        {
            scanf("%lld%lld",&obj[i].v,&obj[i].w);
            obj[i].xjb = obj[i].w*1.0/obj[i].v;
            mn = min(mn,obj[i].v);
        }

        sort(obj,obj+n);

        ans = 0;
        c = clock();
        dfs(0,0,v);

        printf("%lld\n",ans);
    }

    return 0;
}

你可能感兴趣的:(HDOJ)