題意:
t 組測試數據,n個零件,b元錢;
n個零件的信息:種類、名稱、價格、質量;
每種零件買一個,組裝電腦,電腦性能由所有配件中質量最小的那個決定,求b元錢能組裝的電腦的最大性能
思路:
二分性能範圍,然後利用貪心,儘量拿錢數最小的去組合;
如果能組合出來,說明最優解在右邊,如果不能,說明最優解在左邊,直到區間趨近爲止
代碼如下:
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
#define inf 1000000005
using namespace std;
struct node
{
char type[25];
int price, quality;
}cp[1005];
int budget;
int n, tmp;
bool cmp(node a, node b)
{
if(strcmp(a.type, b.type) == 0)
return a.price < b.price;
return strcmp(a.type, b.type) < 0;
}
bool check(int x)
{
int cnt = 0, sum = 0;
bool flag = 0;
for(int i = 0; i < n; i++)
{
if(flag == 1 && strcmp(cp[i].type, cp[i - 1].type) == 0) continue;
if((sum + cp[i].price) <= budget && cp[i].quality >= x)
{
sum += cp[i].price; flag = 1; cnt++;
}
else flag = 0;
}
if(sum <= budget && cnt == tmp && flag) return true;
else return false;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
int l = 0, r = 0;
char s[25];
scanf("%d%d", &n, &budget);
for(int i = 0; i < n; i++)
{
scanf("%s", cp[i].type);
scanf("%s", s);
scanf("%d%d", &cp[i].price, &cp[i].quality);
r = max(r, cp[i].quality);
}
sort(cp, cp+n, cmp);
tmp = 1;
for(int i = 1; i < n; i++)
{
if(strcmp(cp[i].type, cp[i - 1].type) != 0) tmp++;
}
int mid;
while(l < r)
{
mid = (l + r) / 2;
if (l == mid) break;
if (check(mid))
l = mid;
else r = mid;
}
if (check(mid + 1)) mid++;
printf("%d\n", mid);
}
return 0;
}