CF - The Party and Sweets

Authors: Jesse Choe, Brad Ma

Official Editorial

Solution (Greedy)

Let's consider the following example:

2 2
0 1
1 0

The answer to this example is 1-1 since boy 22 ends up giving girl 22 too many sweets, even if boy 22 gives girl 22 the minimum number of sweets he could possibly give, which is 11. However, girl 22 received a maximum of no sweets, making it impossible.

If a single boy gives more sweets than a girl received, then any arrangement of sweets is impossible with the constraints. More formally, if

max(b1,b2,,bn1,bn)>min(g1,g2,,gm1,gm),\max(b_1, b_2, \dots, b_{n-1}, b_n) > \min(g_1, g_2, \dots, g_{m-1}, g_m),

then the answer is 1-1.

If the input provided has an arrangement of sweets that follow the given constraints, then we can greedily find the answer.

Since our objective is to minimize the total number of sweets given out, let's first consider a lower bound on the answer. Since the fewest number of sweets boy ii gives each girl is bib_i, he gives out a total of at least bimb_i \cdot m sweets. Thus, the answer to this problem is lower bounded by i=1nbim\sum\limits_{i=1}^{n} b_i \cdot m.

We are not done yet, however. The previous sum does not necessarily satisfy the condition that gig_i is the maximum number of sweets a single girl received. Each girl jj has some boy ii who gave her gjg_j sweets instead of bib_i sweets. This raises our lower bound by gjbig_j-b_i. We would like to choose ii such that bib_i is maximal. Since we know max(b)min(g)\max(b) \leq \min(g), we would always choose the boy who gives the most sweets.

However, this boy still must give bib_i sweets to some girl; thus if no gjg_j is equal to bib_i, then he needs to have given some girl bib_i sweets and the boy who gives the second most sweets can give this girl her maximal sweets.

Time Complexity: O(NlogN+MlogM)\mathcal{O}(N\log N + M\log M)

C++

C++ Implementation

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int n, m;
cin >> n >> m;
vector<int> b(n), g(m);

Java

import java.io.*;
import java.util.*;
public class ThePartyAndSweets {
public static void main(String[] args) {
Kattio io = new Kattio();
int n = io.nextInt();
int m = io.nextInt();

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!