#include #include #include #include using namespace std; bool cmp(pair& a, pair& b) { return a.second > b.second; } vector> sort(map& M) { vector> A; for (auto& it : M) { A.push_back(it); } sort(A.begin(), A.end(), cmp); return A; } int main() { long long n, k; cin >> n >> k; map attributes; for (int i = 0; i < n; i++) { string at; long long s; cin >> at >> s; attributes[at] = s; } int l; cin >> l; vector> events; for (int i = 0; i < l; i++) { string at; long long s; cin >> at >> s; events.push_back(make_pair(at, s)); long long cur = attributes[at]; if (cur < s) { long long diff = s - cur; k -= diff; attributes[at] += diff; } } if (k < 0) { cout << 0 << endl; return 0; } map potentialScore; map counts; for (int i = 0; i < l; i++) { auto e = events[i]; if (e.second == attributes[e.first]) { // This will give us the whole score potentialScore[e.first] = potentialScore[e.first] + e.second + 1; } else { // This will give us one more point potentialScore[e.first] = potentialScore[e.first] + 1; } counts[e.first]++; } auto sortedScores = sort(potentialScore); auto maxCount = max_element(begin(counts), end(counts), [] (const pair & p1, const pair & p2) { return p1.second < p2.second; } ); for (auto it = sortedScores.begin(); it != sortedScores.end(); it++) { // If we have an element that gives us at least the same amount of extra points by just adding one, // stop assigning if (maxCount->second > it->second) { break; } if (k == 0) { break; } // Add a point to this attribute attributes[it->first]++; k--; } attributes[maxCount->first] += k; long long score = 0; for (int i = 0; i < l; i++) { auto e = events[i]; if (attributes[e.first] > e.second) { score += attributes[e.first]; } } cout << score << endl; return 0; }