照着思路敲了一下二分答案,发现很神奇。M = L + (R - L + 1) / 2 为什么能一定逼近答案呢,有没有可能这个答案根本不存在,只是在两个答案之间。
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <iostream>
#include <string>
#include <map>
#include <vector>
#define MAXN 100
using std::cin;
using std::cout;
using std::endl;
using std::map;
using std::string;
using std::vector;
using std::min;
using std::max;
map<string, int> id;
//
int cnt;
int n, b;
int ID(string s) {
if (!id.count(s)) id[s] = cnt ++;
return id[s];
}
struct P {
int price, quality;
};
vector<P> comp[1010];
bool check(int q) {
int sum = 0;
for (int i = 0; i < cnt; ++ i) {
int Min = b + 1;
for (int j = 0; j < comp[i].size(); ++ j) {
if (comp[i][j].quality >= q)
Min = min(comp[i][j].price, Min);
}
sum += Min;
if (sum > b) return false;
}
return true;
}
int main() {
//freopen("input.in", "r", stdin);
//freopen("1.out", "w", stdout);
int t;
cin >> t;
while (t --) {
cin >> n >> b;
for (int i = 0; i < n; ++ i) comp[i].clear(); id.clear();
cnt = 0;
int Max = 0;
for (int i = 0; i < n; ++ i) {
string type, name;
int p, q;
cin >> type >> name >> p >> q;
Max = max(Max, q);
comp[ID(type)].push_back((P){p, q});
}
int L = 0, R = Max;
while (L < R) {
//cout << L << " " << R << endl;
//puts("ok");
//int M = (L + R + 1) >> 1;
int M = L + (R - L + 1) / 2;
if (check(M)) L = M;
else R = M - 1;
}
cout << L << endl;
}
}