Posts

Showing posts from 2015

(URI) Notas e Moedas - Solução

Image
Desempenho no URI: import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));             String linha = br.readLine();         String[] dinheiro = new String[2];         dinheiro = linha.split("\\.");         int notas = Integer.parseInt(dinheiro[0]);         int moedas = Integer.parseInt(dinheiro[1]);                 int restoNotas = 0;                 int notasCem = notas/100;               restoNotas = (notas-notasCem*100);                int notasCinquenta = restoNotas/50;         restoNotas -= notasCinquenta*50;         int notasVinte = restoNotas/20;         restoNotas -= notasVinte*20;         int notasDez = restoNotas/10;         restoNotas -= notasDez*10;         int notasCinco = restoNotas/5;         restoNotas -= notasCinco*5;         int notasDois = restoNotas/2;         restoNotas -= notasDois*2;  

(URI) Teste de Seleção 1 - Solução

import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));             int a = leitor(br);         int b = leitor(br);         int c = leitor(br);         int d = leitor(br);                 if (a%2 == 0 && c > 0 && d > 0 && b > c && d > a && (c+d) > (a+b)) {             System.out.println("Valores aceitos");         }         else {             System.out.println("Valores nao aceitos");         }     }         static int leitor(BufferedReader br) throws NumberFormatException, IOException {               int n;         int resp = 0;                       while (true) {                       n = br.read();                       if (n >= '0' && n <= '9')                 break;              }                       while (true)

(URI) Ho Ho Ho - Solução

import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));         int qteHo = leitor(br);                 for (int i = 0; i < qteHo-1; i++) {             bw.write("Ho ");         }         bw.write("Ho!\n");                 bw.flush();         bw.close();     }     static int leitor(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;     } }

(URI) Cédulas - Solução

import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));             int dinheiro = leitor(br);         int dif = 0;                 int cem = dinheiro/100;               dif = (dinheiro-cem*100);                int cinquenta = dif/50;         dif -= cinquenta*50;         int vinte = dif/20;         dif -= vinte*20;         int dez = dif/10;         dif -= dez*10;         int cinco = dif/5;         dif -= cinco*5;         int dois = dif/2;         dif -= dois*2;         int um = dif;         System.out.println(dinheiro);         System.out.println(cem + " nota(s) de R$ 100,00");         System.out.println(cinquenta + " nota(s) de R$ 50,00");         System.out.println(vinte + " nota(s) de R$ 20,00");         System.out.println(dez + " nota(s) de R$ 10,00");         System.out.println(c

(URI) Conversão de Tempo - Solução

import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));             int totalSegundos = leitor(br);                 int segundos = totalSegundos%60;         int minutos = (totalSegundos/60)%60;         int horas = (totalSegundos/60)/60;                 System.out.println(horas+":"+minutos+":"+segundos);     }         static int leitor(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 >

(URI) Distância - Solução

import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));            int distancia = leitor(br);                System.out.println((distancia+distancia) + " minutos");     }        static int leitor(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;       } }

(URI) Distância Entre Dois Pontos - Solução

import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));             String linha = br.readLine();         StringTokenizer tokenizer = new StringTokenizer(linha);                    double x1 = Double.parseDouble(tokenizer.nextToken());         double y1 = Double.parseDouble(tokenizer.nextToken());                 linha = br.readLine();         tokenizer = new StringTokenizer(linha);                    double x2 = Double.parseDouble(tokenizer.nextToken());         double y2 = Double.parseDouble(tokenizer.nextToken());                 double distancia = Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));                 System.out.printf("%.4f\n", distancia);     } }

(URI) O Maior - Solução

import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));             int a = leitor(br);         int b = leitor(br);         int c = leitor(br);                 int maior = (a + b + Math.abs(a-b))/2;                 maior = (maior + c + Math.abs(maior-c))/2;                 System.out.println(maior + " eh o maior");     }         static int leitor(BufferedReader br) throws NumberFormatException, IOException {               int n;         int resp = 0;               int sinal = 1;                       while (true) {                       n = br.read();                       if (n >= '0' && n <= '9')                 break;             if (n == '-')                 sinal = -1;                       if (n == '+')                 sinal = 1;               }                  

(URI) Área - Solução

import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));             String linha = br.readLine();                 StringTokenizer tokenizer = new StringTokenizer(linha);         double a = Double.parseDouble(tokenizer.nextToken());         double b = Double.parseDouble(tokenizer.nextToken());         double c = Double.parseDouble(tokenizer.nextToken());                 System.out.print("TRIANGULO: ");         System.out.printf("%.3f\n", (a*c)/2);                 System.out.print("CIRCULO: ");         System.out.printf("%.3f\n", 3.14159*(c*c));                 System.out.print("TRAPEZIO: ");         System.out.printf("%.3f\n", ((a+b)*c)/2);                 System.out.print("QUADRADO: ");         System.out.printf("%.3f\n", b*b);                 S

(URI) Cálculo Simples - Solução

import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                 double total = 0.0;                 for (int i = 0; i < 2; i++) {             String linha = br.readLine();                         StringTokenizer tokenizer = new StringTokenizer(linha);             int codigo = Integer.parseInt(tokenizer.nextToken());             int qte = Integer.parseInt(tokenizer.nextToken());             double preco = Double.parseDouble(tokenizer.nextToken());                         total += qte*preco;         }                        System.out.print("VALOR A PAGAR: R$ ");         System.out.printf("%.2f\n", total);     } }

(URI) Esfera - Solução

import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                 int raio = leitor(br);                 double volume = (4.0/3.0) * 3.14159 * Math.pow(raio, 3);                 System.out.print("VOLUME = ");         System.out.printf("%.3f\n", volume);     }         static int leitor(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;     } }

(URI) Mergulho - Solução

import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));         String linha;                 while ((linha = br.readLine()) != null) {             StringTokenizer tokenizer = new StringTokenizer(linha);             int numVoluntarios = Integer.parseInt(tokenizer.nextToken());             int retornaram = Integer.parseInt(tokenizer.nextToken());                                     int[] listaPresenca = new int[numVoluntarios];                      for (int i = 0; i < retornaram; i++) {                 int identificador = leitor(br);                 listaPresenca[identificador-1] = 1;             }                         boolean todosVoltaram = true;             for (int i = 0; i < numVoluntarios; i++) {                 if (listaPresen

(URI) Tipo de Combustível - Solução

import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                 int valor = leitor(br);         int alcool = 0;         int gasolina = 0;         int diesel = 0;                while (valor != 4) {             switch(valor) {                 case 1:                     alcool++;                     break;                 case 2:                     gasolina++;                     break;                 case 3:                     diesel++;                     break;                 default:                     break;             }                         valor = leitor(br);                }         System.out.println("MUITO OBRIGADO\nAlcool: " + alcool + "\nGasolina: " + gasolina + "\nDiesel: " + diesel);     }     static int leitor(BufferedReader br) throws NumberFormatException, IOExc

(URI) Substituição em Vetor I - Solução

import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));         for (int i = 0; i < 10; i++) {             int valor = leitor(br);                         if (valor <= 0) {                 valor = 1;             }             bw.write("X["+i+"] = "+ valor +"\n");         }         bw.flush();                bw.close();     }     static int leitor(BufferedReader br) throws NumberFormatException, IOException {        int n;        int resp = 0;        int sinal = 1;        while (true) {            n = br.read();            if (n >= '0' && n <= '9') break;            if (n == '-') sinal = -1;            if (n == '+') sinal = 1;        }        while (true) {     

(URI) Preenchimento de Vetor II - Solução

import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));         int valor = leitor(br);                 int imprime = 0;         for (int i = 0; i < 1000; i++) {             bw.write("N["+i+"] = "+ imprime +"\n");             if (++imprime == valor) {                 imprime = 0;             }         }         bw.flush();                bw.close();     }     static int leitor(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 &

(URI) Preenchimento de Vetor III - Solução

import java.io.*; import java.util.*; import java.text.DecimalFormat; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));         double valor = Double.parseDouble(br.readLine());         DecimalFormat df = new DecimalFormat("0.0000");                 for (int i = 0; i < 100; i++) {             bw.write("N["+i+"] = "+ df.format(valor)+"\n");                         valor /= 2.0000;         }         bw.flush();                bw.close();     } }

(URI) Maior e Posição - Solução

import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                int posicao = 1;         int maior = -1;         for (int i = 0; i < 100; i++) {             int x = leitor(br);                        if (x > maior) {                 maior = x;                 posicao = i+1;             }         }         System.out.println(maior+"\n"+posicao);     }     static int leitor(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;     } }

(URI) Soma de Ímpares Consecutivos II - Solução 2

Versão utilizando a Soma dos Termos de uma Progressão Aritmética, objetivando a eliminação do loop. Para isto, precisamos saber o primeiro e o último valores ímpares a serem considerados e a quantidade de elementos que existirá nesta PA. Veja mais sobre Progressão Aritmética aqui . import java.io.*; import java.util.*; import java.math.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));                 int entradas = leitor(br);                 for (int i = 0; i < entradas; i++) {             int x = leitor(br);             int y = leitor(br);                         if (x != y) {                 int maior = Math.max(x, y);                 int menor = Math.min(x, y);                             int primeiro = -1;                 int ultimo = -1;                 i

(URI) Soma de Ímpares Consecutivos II - Solução 1

import java.io.*; import java.util.*; import java.math.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));                 int entradas = leitor(br);                 for (int i = 0; i < entradas; i++) {             int x = leitor(br);             int y = leitor(br);                         int maior = Math.max(x, y);             int menor = Math.min(x, y);                     int soma = 0;             for (int j = menor+1; j < maior; j++) {                 if (j%2 == 1) {                     soma += j;                 }             }                         bw.write(soma+"\n");         }         bw.flush();                bw.close();     }     static int leitor(BufferedReader br) throws NumberFormatException, IOException {        int n;        int resp = 0

(URI) Jogando Cartas Fora - Solução 2

Image
Esta solução é mais eficiente do que a Solução 1, pois: Utilizamos o StringBuilder para construir as strings com as respostas; Utilizamos o BufferedWriter para imprimir as respostas; Descobrimos primeiro todas as respostas para as 50 entradas possíveis, armazenando-as em um vetor. Em seguida, dadas as entradas, pesquisamos no vetor de respostas as saídas correspondentes. Desempenho no URI: import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));                 String[] respostas = new String[50];         for (int i = 0; i < 50; i++) {             StringBuilder sb = new StringBuilder();                         int qteCartas = i+1;                         ArrayList<Integer> pilha = new ArrayList<Integer>();        

(URI) Jogando Cartas Fora - Solução 1

Esta solução não é a mais eficiente. import java.io.*; import java.util.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));                 int qteCartas = leitor(br);                 while (qteCartas != 0) {             ArrayList<Integer> pilha = new ArrayList<Integer>();             insere(qteCartas, pilha);             bw.write("Discarded cards: ");                         int topo = 0;             while (qteCartas > 1) {                 if (topo > 0) {                     bw.write(", ");                 }                 bw.write(String.valueOf(pilha.get(topo)));                 topo++; // simula uma remoção da pilha                 qteCartas--; // por remover uma carta                 realoca(topo, pilha); // coloca a carta no

(URI) Trigo no Tabuleiro - Solução

Para este problema é necessário utilizar o BigInteger , pois dadas as entradas possíveis, poderemos ter que calcular 2^64, que não é suportado pelo int ou pelo long . Não sabe utilizar o BigInteger? Veja aqui e aqui . import java.io.*; import java.util.*; import java.math.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                 int qte = leitor(br);                 for (int i = 0; i < qte; i++) {             int quadrados = leitor(br);             BigInteger base = BigInteger.valueOf(2);             BigInteger qteTrigo = base.pow(quadrados);                                     System.out.println(qteTrigo.divide(BigInteger.valueOf(12000)) + " kg");         }     }         static int leitor(BufferedReader br) throws NumberFormatException, IOException {        int n;        int resp = 0;        int sinal =

(URI) Encaixa ou Não I - Solução

import java.io.*; import java.util.*; import java.lang.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                 int qte = leitor(br);                 for (int i = 0; i < qte; i++) {             String s = br.readLine();             String[] ss = s.split(" ");                         boolean encaixa = true;             if (ss[1].length() <= ss[0].length()) {                 int ultimo = ss[0].length()-1;                 for (int j = ss[1].length()-1; j >= 0; j--, ultimo--) {                     if (ss[1].charAt(j) != ss[0].charAt(ultimo)) {                         encaixa = false;                     }                 }             }             else {                 encaixa = false;             }                         if (encaixa) {                 System.out.println("encaixa");     

(URI) Número Primo - Solução

import java.io.*; import java.util.*; import java.lang.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                 int qte = leitor(br);                 for (int i = 0; i < qte; i++) {             boolean primo = true;             int numero = leitor(br);             for (int j = 2; j < numero; j++) {                 if (numero%j == 0) {                     primo = false;                     break;                 }             }             if (primo) {                 System.out.println(numero + " eh primo");             }             else {                 System.out.println(numero + " nao eh primo");             }         }     }         static int leitor(BufferedReader br) throws NumberFormatException, IOException {        int n;        int resp = 0;        int sinal = 1;        while