|
| 1 | + |
| 2 | + |
| 3 | +import java.util.Map; |
| 4 | +import java.util.Scanner; |
| 5 | +import java.util.HashMap; |
| 6 | + |
| 7 | +/* @author santi @fecha 26 ene. 2024*/ |
| 8 | +public class ProblemaA { |
| 9 | + public static void main(String[] args) { |
| 10 | + Scanner sc = new Scanner(System.in); |
| 11 | + |
| 12 | + //llegeixo cada cas de prova mentre n'hi hagi (condició finalitzacio nVots == 0, dins bucle amb break |
| 13 | + while (true) { |
| 14 | + Map<String, Integer> paisVots = new HashMap<>(); //declaro un nou hashMap (mapa) |
| 15 | + int nVots = sc.nextInt(); //llegeixo nombre de vots esperats (nre strings) |
| 16 | + sc.nextLine(); //netejo bufer |
| 17 | + |
| 18 | + //CAS EN QUE S'ACABA LA SEQUÈNCIA |
| 19 | + if (nVots == 0) |
| 20 | + break; |
| 21 | + |
| 22 | + //LLEGEIXO ELS STRINGS (PAISOS) I ELS CONTO DINS |
| 23 | + //CADA VALOR DE LA CLAU CORRESPONENT (PER A UN CAS DE PROVA DONAT) |
| 24 | + String pais = ""; |
| 25 | + for (int i = 0; i < nVots; ++i) { |
| 26 | + pais = sc.next(); //llegeixo paraula a paraula |
| 27 | + if (paisVots.containsKey(pais)) //el pais ja ha sigut afegit a dins el map (sumem +1 als vots existents) |
| 28 | + paisVots.put(pais, paisVots.get(pais) + 1); |
| 29 | + else //el pais no existeix dins el map (posem un vot) |
| 30 | + paisVots.put(pais, 1); |
| 31 | + } |
| 32 | + |
| 33 | + |
| 34 | + //MIRO EL PAIS GUANYADOR O SI HI HA EMPATS (EL HASMAP ESTÀ ORDENAT) |
| 35 | + //I SI HI HA UN SOL PAIS NO CAL MIRAR EL HASH |
| 36 | + if (paisVots.size() == 1) |
| 37 | + System.out.println(pais); |
| 38 | + else { |
| 39 | + |
| 40 | + //primera posicio es el pais amb mes vots. Segona posicio es el |
| 41 | + //segon pais amb mes vots. Si coincideixen hi ha empat |
| 42 | + |
| 43 | + int maxVots = 0; //sempre hi haurà com a minim un vot aixi que 0 es un enter que podem escollir. |
| 44 | + String paisMaxVots = ""; |
| 45 | + |
| 46 | + //RECORREM EL MAP PER TROBAR ELS PAISOS MES VOTATS |
| 47 | + //BOOLEA empat clau per resoldre els empats (ha COSTAT!) |
| 48 | + boolean empat = false; |
| 49 | + for (Map.Entry<String, Integer> parell_paisVot : paisVots.entrySet()) { |
| 50 | + |
| 51 | + String paiset = parell_paisVot.getKey(); |
| 52 | + int votetsPaiset = parell_paisVot.getValue(); |
| 53 | + |
| 54 | + //System.out.printf("pais: %s", paiset); |
| 55 | + //System.out.printf("| vots: %d\n", votetsPaiset); |
| 56 | + |
| 57 | + if (votetsPaiset > maxVots) { |
| 58 | + maxVots = votetsPaiset; |
| 59 | + paisMaxVots = paiset; |
| 60 | + empat = false; |
| 61 | + } else if (votetsPaiset == maxVots) |
| 62 | + empat = true; |
| 63 | + } |
| 64 | + |
| 65 | + //IMPRIMIM EL RESULTAT PER PANTALLA |
| 66 | + if (empat) |
| 67 | + System.out.println("EMPATE"); |
| 68 | + else |
| 69 | + System.out.println(paisMaxVots); |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments