传送门UVa Live Archive 3971 & UVa 12124 & POJ 3497 - Assemble
题意:大家都知道,电脑的质量是取决于他的部件中质量最差的。(话说这句话我理解了好久XD)现在小明要买一台电脑,我们要帮他选出最差的质量最好。。也就是说,最小值最大化。
一天一道算法题里说过,最小值最大化一般都是用二分。
在这题里
1、如何得到结果?
对质量进行二分。比如说,最差的质量是2,最好的质量是10.二分一下,得到mid = 6,这时候就把质量为6验证一下,看这时候选出来的部件的总价有没有超过预算,或者这时候有某个部件根本没有质量>=6的选择。
如果上两个都符合,OK,说明最差质量为6是可以得到的,这时候继续二分,7 + (10 - 7)/ 2 = 8.同样,验证质量为8的时候能否满足。以此类推,直到循环退出。
2、如何对各个部件进行分组?
因为要对每个部件都进行挑选,所以必须把它们分组。这时候采用的是map + vector【】【】。
拿到部件的名称后,用map.count看以前出现过没有,如果有的话,就有一个int值,就是它所属的类别,换言之,一个类别的部件都集中在同一个vector[i]里。
本来想排序一下再用lower_bound找的,但是一想,题目又没说质量越高价钱越高。。然后我就扫描一遍数组了。。
#include <cstdio>
#include <vector>
#include <algorithm>
#include <map>
#include <string>
using namespace std;
const int MAXN = 1100;
const int BIG = 2147483647;
struct COMPONENTS
{
int price, quality;
char type[50], name[50];
};
int cnt, money;
bool isOK(const vector<COMPONENTS> *ve, int target)
{
int sum = 0;
for (int i = 0; i < cnt; i++)
{
int cheapest = BIG;
for (int j = 0; j < ve[i].size(); j++)
{
if (ve[i][j].quality >= target && ve[i][j].price < cheapest)
cheapest = ve[i][j].price;
}
if (cheapest == BIG)
return false;
sum += cheapest;
if (sum > money)
return false;
}
return true;
}
int main()
{
//freopen("input.txt", "r", stdin);
int T, i, j, n, maxQua, minQua, ans;
map<string, int> mp;
COMPONENTS temp;
scanf("%d", &T);
while (T--)
{
ans = -1;
mp.clear();
vector<COMPONENTS> ve[MAXN];
cnt = 0;
maxQua = -1;
minQua = BIG;
scanf("%d%d", &n, &money);
for (i = 0; i < n; i++)
{
scanf("%s%s%d%d", temp.type, temp.name, &temp.price, &temp.quality);
if (!mp.count(temp.type))
mp[temp.type] = cnt++;
ve[mp[temp.type]].push_back(temp);
minQua = min(minQua, temp.quality);
maxQua = max(maxQua, temp.quality);
}
int left = minQua, right = maxQua + 1, mid;
while (left < right)
{
mid = left + (right - left) / 2;
if (isOK(ve, mid))
{
ans = mid;
left = mid + 1;
}
else
right = mid;
}
printf("%d\n", ans);
}
return 0;
}