(SPOJ) Olimpíadas - Solution

Link to the problem: http://br.spoj.com/problems/OLIMP09/

This is another problem where we only need to sort a structure.


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

class Main {
    public static int reader(BufferedReader br) throws NumberFormatException, IOException {     
        int n;
        int resp = 0;     
      
        while (true) {         
            n = br.read();         
            if (n >= '0' && n <= '9') {
                break;
            }
        }
           
        while (true) {         
            resp = resp*10 + n-'0';         
            n = br.read();         
            if (n < '0' || n > '9') {
                break;     
            }
        }
      
        return resp;     
    }
   
    public void process() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int numCountries = reader(br);
        int numModalities = reader(br);
       
        Medal[] medals = new Medal[numCountries];
        for (int i = 0; i < numCountries; i++) {
            medals[i] = new Medal(i, 0, 0, 0);
        }
       
        for (int i = 0; i < numModalities; i++) {
            int gold = reader(br);
            int silver = reader(br);
            int bronze = reader(br);
            medals[gold-1].gold += 1;
            medals[silver-1].silver += 1;
            medals[bronze-1].bronze += 1;
        }
        br.close();
        Arrays.sort(medals);
               
        for (int i = 0; i < numCountries; i++) {
            if (i == numCountries-1) {
                bw.write((medals[i].id+1) + "\n");
                break;
            }
            bw.write((medals[i].id+1) + " ");
        }
       
        bw.flush();
        bw.close();
               
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
       
        System.exit(0);
    }
}

class Medal implements Comparable<Medal> {
    int id;
    int gold;
    int silver;
    int bronze;
   
    public Medal(int id, int gold, int silver, int bronze) {
        this.id = id;
        this.gold = gold;
        this.silver = silver;
        this.bronze = bronze;
    }
   
    public int compareTo(Medal m) {
        if (m.gold-this.gold == 0) {
            if (m.silver-this.silver == 0) {
                if (m.bronze-this.bronze == 0) {
                    return this.id-m.id;
                }
                return m.bronze-this.bronze;
            }
            return m.silver-this.silver;
        }
        return m.gold-this.gold;
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução