Hoj 2608 Assemble

题目:http://acm.hit.edu.cn/hoj/problem/view?id=2608

题意:某人要组装电脑,有资金限制。各个种类的配件必须选购其中一个,相同种类的不同质量系数的配件有不同的金额,组装后的电脑的性能由最低质量系数的配件绝对,问:如何在已有资金条件下,选购配件,使得最后的电脑性能最高。

比赛时,我想应该是一种背包问题的变型,其实本题可以用二分法来做:求出所有质量中最大与最小的,然后按照质量和种类排序部件,然后二分查找这些部件中是否满足该质量的价格条件,满足更新即可。

另外:

即使价格和质量不是正比关系,本方法也是适用的。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <map>
#include <string>
using namespace std;

struct Machine
{
    char type[25];
    char name[25];
    int price;
    int quality;

};

Machine mac[1005];
int kind[1005];
int num;
int b;

bool cmp(Machine a,Machine b)
{
    return strcmp(a.type,b.type)<0 || (strcmp(a.type,b.type) == 0 && a.quality<b.quality);
}

bool judge(int mid)
{
    int sum = 0;
    for(int i=0;i<=num-2;i++)
    {
        int min = 0x3f3f3f3f;
        for(int j=kind[i];j<kind[i+1];j++)
        {
            if(mac[j].quality>=mid)
            {
                min = (mac[j].price < min ? mac[j].price : min);
                //break;
            }
        }
        if(min == 0x3f3f3f3f)
        {
            return false;
        }
        sum += min;
    }
    if(sum<=b)
    {
        return true;
    }
    else
    {
        return false;
    }
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
    int t;
    int n;
    scanf(" %d",&t);
    while(t--)
    {
        scanf(" %d %d",&n,&b);
        //所有质量的最大值
        int max = 0;
        //所有质量的最小值
        int min = 0x3f3f3f3f;

        for(int i=0;i<n;i++)
        {
            scanf(" %s %s %d %d",mac[i].type,mac[i].name,&mac[i].price,&mac[i].quality);
            max = (max < mac[i].quality ? mac[i].quality : max);
            min = (min > mac[i].quality ? mac[i].quality : min);
        }

        sort(mac,mac+n,cmp);
        memset(kind,0,sizeof(kind));
        num = 1;
        for(int i=1;i<n;i++)
        {
            if(strcmp(mac[i].type,mac[i-1].type)!=0)
            {
                kind[num++] = i;
            }
        }
        kind[num++] = n;

        int low = min;
        int high = max;
        int res = 0;
        //即使价格和质量不是正比关系,也可以用二分
        while(low<=high)
        {
            int mid = (low + high)>>1;
            if(judge(mid))
            {
                res = mid;
                low = mid + 1;
            }
            else
            {
                high = mid - 1;
            }
        }

        printf("%d\n",res);
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值