Posts

Showing posts from January, 2016

(UVA) Knight Moves - Solução 2

You can see another solution for this problem here . The difference between the solution mentioned above and this new one is that, for this case, I do not use the adjacency list. Then, I have changed the Breadth-First Search method. Now, I only look for the "reachable nodes" when I am in this method. Comparing the run time between the two solutions: - The first one ran in: 0.462s. - The second one ran in: 0.365s. The solution from 2014 ran in 0.612s. import java.io.*; import java.util.*; class Main  {     public static final int MAX = 8;             public static int bfs(int startR, int startC, int goalR, int goalC) {         int[] vi = {2,2,-2,-2,1,1,-1,-1};         int[] vj = {1,-1,1,-1,2,-2,2,-2};                 Queue<Element> queue = new ArrayDeque<Element>();         Element e = new Element(startR, startC, 0);         queue.add(e);                 HashSet<Integer> addedToQueue = new HashSet<Integer>();         addedToQueue.add(startR*M

(UVA) Knight Moves - Solução 1

If you want to see another solution developed in 2014 , click here . import java.io.*; import java.util.*; class Main  {     public static final int MAX = 8;     public static HashMap<Integer, ArrayList<Integer>> adjList = new HashMap<Integer, ArrayList<Integer>>();        public static int bfs(int start, int goal) {         Queue<Element> queue = new ArrayDeque<Element>();         Element e = new Element(start, 0);         queue.add(e);                HashSet<Integer> addedToQueue = new HashSet<Integer>();         addedToQueue.add(start);                while (queue.size() > 0) {             int currPos = queue.element().pos;             if (currPos == goal) {                 return queue.element().distance;             }                        ArrayList<Integer> reachable = adjList.get(currPos);             for (int i = 0; i < reachable.size(); i++) {                 if (!addedToQueue.contains(reachable.get(i))) {         

(SPOJ) Árvore Genealógica - Solução 2

Faster solution than the previous one ( here ). It uses BufferedReader and BufferedWriter instead of Scanner and System.out, respectively . The BufferedWriter change does not have a considerable impact because the output is small. In addition, some improvements have been done in the Breadth-First Search method. import java.io.*; import java.util.*; class Main  {     public static HashMap<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>();     public static String nameDest = "";        public static void printAnswer(String startName, String finalName, int biggerDegree) throws NumberFormatException, IOException {         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));         if (startName.compareTo(finalName) < 0) { // if the first name comes first (alphabetic order)             bw.write(startName + " " + finalName + " " + biggerDegree + "\n");         }      

(SPOJ) Árvore Genealógica - Solução 1

import java.io.*; import java.util.*; class Main  {     public static HashMap<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>();     public static String nameDest = "";         public static void printAnswer(String startName, String finalName, int biggerDegree) {         if (startName.compareTo(finalName) < 0) { // if the first name comes first (alphabetic order)             System.out.println(startName + " " + finalName + " " + biggerDegree);         }         else { // if the second name comes first (alphabetic order)             System.out.println(finalName + " " + startName + " " + biggerDegree);         }     }         public static int bfs(String start) {         HashSet<String> visited = new HashSet<String>();         Queue<String> queue = new LinkedList<String>();         queue.add(start);                 int count = 0;         Queue<Integer> di

(UVA) Shipping Routes - Solução 2

In this solution, the Breadth-First Search method was improved from the previous solution ( here ). Moreover, instead of using two queues (queue and distance), it was created one queue which holds 'Element' objects, which h as both values. import java.io.*; import java.util.*; class Main  {     public static HashMap<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>();         public static int bfs(String start, String goal) {         Queue< Element > queue = new ArrayDeque< Element >();         Element e = new Element (start, 0);         queue.add( e );                 HashSet<String> addedToQueue = new HashSet<String>();         addedToQueue.add(start);                 while (queue.size() > 0) {             String current = queue.element().vertex;             if (current.equals(goal)) {                 return queue.element().distance;             }                         ArrayList<String>

(UVA) Shipping Routes - Solução 1

import java.io.*; import java.util.*; class Main  {     public static HashMap<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>();         public static int bfs(String start, String goal) {         HashSet<String> visited = new HashSet<String>();                 Queue<String> queue = new LinkedList<String>();         queue.add(start);                 int count = 0;         Queue<Integer> distance = new LinkedList<Integer>(); // it will keep the distance between the current warehouse and the start         distance.add(count);                 while (queue.size() > 0) {             String current = queue.poll();             if (visited.contains(current)) {                 continue;             }                            if (current.equals(goal)) {                 return distance.element();             }                         visited.add(current);             distance.remove();             count++;

(URI) Acima da Diagonal Secundária - Solução

import java.io.*; import java.util.*; class Main  {     static final int NUM = 12;     static int total;     public static void readMatrix(Scanner sc, float[][] matrix) {         for (int i = 0; i < NUM; i++) {             for (int j = 0; j < NUM; j++) {                 matrix[i][j] = sc.nextFloat();             }         }     }         public static float calcSum(float[][] matrix) {         float sum = 0;         int limit = NUM;         total = 0;                 for (int i = 0; i < NUM; i++) {             limit--;             for (int j = 0; j < limit ; j++) {                 sum += matrix[i][j];                 total++;             }         }                 return sum;     }         public static void printAnswer(String s, float sum) {         if (s.equals("S")) {             System.out.println(String.format("%.1f", sum));         }         else {             System.out.println(String.format("%.1f", sum/total));         }     }         p

(URI) Linha na Matriz - Solução

import java.io.*; import java.util.*; class Main  {     static final int NUM = 12;     public static void readMatrix(Scanner sc, float[][] matrix) {         for (int i = 0; i < NUM; i++) {             for (int j = 0; j < NUM; j++) {                 matrix[i][j] = sc.nextFloat();             }         }     }         public static float calcSum(int line, float[][] matrix) {         float sum = 0;                 for (int i = 0; i < NUM; i++) {             sum += matrix[line][i];         }                 return sum;     }         public static void printAnswer(String s, float sum) {         if (s.equals("S")) {             System.out.println(String.format("%.1f", sum));         }         else {             System.out.println(String.format("%.1f", sum/NUM));         }     }         public static void process() throws NumberFormatException, IOException {            Scanner sc = new Scanner(System.in);                 float[][] matrix = new float[NUM]

(URI) Estiagem - Solução

import java.io.*; import java.util.*; import java.text.*; import java.math.*; class Main  {     public static int sumX;     public static int sumY;     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 static void readEntries(BufferedReader br, Consumption[] list, int n) throws NumberFormatException, IOException {       for (int i = 0; i < n; i++) {             int x = reader(br);             int y = reader(br);               

(URI) Números Ímpares - Solução

import java.io.*; import java.util.*; class Main  {     public static void process() throws NumberFormatException, IOException {            Scanner sc = new Scanner(System.in);                 int number = sc.nextInt();         for (int i = 1; i <= number; i+=2) {             System.out.println(i);         }                                 return;     }         public static void main(String[] args) throws NumberFormatException, IOException {         Main m = new Main();         m.process();         System.exit(0);     } }

(URI) Números Pares - Solução

import java.io.*; class Main  {     public static void process() throws NumberFormatException, IOException {            for (int i = 2; i <= 100; i+=2) {             System.out.println(i);         }                                 return;     }         public static void main(String[] args) throws NumberFormatException, IOException {         Main m = new Main();         m.process();         System.exit(0);     } }

(URI) Mês - Solução

import java.io.*; import java.util.*; class Main  {     public static void process() throws NumberFormatException, IOException {            Scanner sc = new Scanner(System.in);                 int month = sc.nextInt();         String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};                 System.out.println(months[month-1]);                                 return;     }         public static void main(String[] args) throws NumberFormatException, IOException {         Main m = new Main();         m.process();         System.exit(0);     } }

(URI) Experiências - Solução

import java.io.*; import java.util.*; class Main  {     public static void process() throws NumberFormatException, IOException {            Scanner sc = new Scanner(System.in);                 String animals = "CRS";         int[] results = new int[4];                 int numTests = sc.nextInt();         for (int i = 0; i < numTests; i++) {             int qty = sc.nextInt();             String op = sc.next();                         results[animals.indexOf(op)] += qty;                        results[3] += qty;         }                 System.out.println("Total: " + results[3] + " cobaias");         System.out.println("Total de coelhos: " + results[0]);         System.out.println("Total de ratos: " + results[1]);         System.out.println("Total de sapos: " + results[2]);         System.out.println("Percentual de coelhos: " + String.format("%.2f", (double)results[0]/results[3]*100) + " %");  

(URI) TDA Racional - Solução

import java.io.*; class Main  {     static int resultN = 0;     static int resultD = 0;                 public static int mdc(int a, int b) {         if (b == 0) {             return a;         }         else {             return mdc(b, a%b);         }     }         public static void calc(String op, int n1, int d1, int n2, int d2) {         switch (op) {             case "+":                 resultN = (n1*d2 + n2*d1);                 resultD = (d1*d2);                 break;             case "-":                 resultN = (n1*d2 - n2*d1);                 resultD = (d1*d2);                 break;             case "*":                 resultN = (n1*n2);                 resultD = (d1*d2);                 break;             case "/":                 resultN = (n1*d2);                 resultD = (n2*d1);                 break;             default:                 break;         }                 if (resultN == 0) {             resultD = 0;         }  

(URI) Conta - Solução

import java.io.*; 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 c = Integer.parseInt(br.readLine());                 for (int i = 0; i < c; i++) {             int n = Integer.parseInt(br.readLine());                         if (n%2 == 0) {                 bw.write("0\n");             }              else {                 bw.write("1\n");             }                         }                 bw.flush();         bw.close();     } }

(URI) Sequencia IJ 2 - Solução

import java.io.*; class Main  {     public static void main(String[] args) throws NumberFormatException, IOException {         for (int i = 1; i < 10; i += 2) {             System.out.println("I=" + i + " J=7");             System.out.println("I=" + i + " J=6");             System.out.println("I=" + i + " J=5");         }     } }

(URI) Identificando o Chá - Solução

import java.io.*; class Main  {     public 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;          }         public static int verify(int tea, BufferedReader br) throws NumberFormatException, IOException {              int count = 0;         for (int i = 0; i < 5; i++) {             int answer = leitor(br);             if (answer == tea) {                 count++;             }         }                 return count;     }         public static vo

(URI) Domingo de Manhã - Solução

import java.io.*; class Main  {     public static void printAnswer(int terminal, int maxTime) {         if (terminal-maxTime <= 0) {             System.out.println("Atraso maximo: 0");         }         else {             System.out.println("Atraso maximo: " + (terminal-maxTime));         }     }         public static void main(String[] args) throws NumberFormatException, IOException {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                 // 8h*60 = 480min         int maxTime = 480;         String time;                 while ((time = br.readLine()) != null) {             String[] hour = time.split(":");                         int terminal = Integer.parseInt(hour[0])*60 + Integer.parseInt(hour[1]) + 60;                printAnswer(terminal, maxTime);                  }     } }