(UVA) A Match Making Problem - Solution

Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=3362

The solution below used a Greedy approach to solve this problem.

The problem states that we should start matching the pairs by the most senior bachelor. Then, we can sort the array related to the bachelors' ages in a descending order. The most senior bachelor available would be linked to the most senior spinster available. Finally, if there is any bachelor that is not linked to a spinster, we present the youngest one by getting the last element in the array of bachelors.


import java.io.*;
import java.util.*;

class Main {
    public void process() throws NumberFormatException, IOException {
        Scanner sc = new Scanner(System.in);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int numCase = 0;
        int numBachelors = sc.nextInt();
        int numSpinsters = sc.nextInt();
        while (numBachelors != 0 || numSpinsters != 0) {
            Integer[] bachelors = new Integer[numBachelors];
            int spinsters = 0; // do not need to keep the age of the spinsters, it will not be used
            for (int i = 0; i < numBachelors; i++) {
                bachelors[i] = sc.nextInt();
            }
            for (int i = 0; i < numSpinsters; i++) {
                spinsters = sc.nextInt();
            }
            Arrays.sort(bachelors, Collections.reverseOrder());
          
            bw.write("Case " + ++numCase + ": " + Math.max(0, (numBachelors-numSpinsters)));
            if (numBachelors-numSpinsters > 0) {
                bw.write(" " + bachelors[numBachelors-1]);
            }
            bw.write("\n");
          
            numBachelors = sc.nextInt();
            numSpinsters = sc.nextInt();
        }
                                             
        bw.flush();
        bw.close();
      
        return;
    }
  
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
      
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução