Posts

Showing posts from February, 2016

(URI) Tempo de Jogo - Solution

import java.io.*; class Main  {     public static void process() throws NumberFormatException, IOException {            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                     String line = br.readLine();            String[] hours = line.split(" ");         int start = Integer.parseInt(hours[0]);         int end = Integer.parseInt(hours[1]);                 int result = 0;         if (start == end) {             result = 24;         }         else if (end < start) {             int day1 = 24-start;             int day2 = end;             result = day1+day2;         }         else {             result = end-start;         }         System.out.println("O JOGO DUROU " + result + " HORA(S)");                         return;     }         public static void main(String[] args) throws NumberFormatException, IOException {         Main m = new Main();         m.process();         System.exit(0);     } }

(UVA) Ordering Tasks - Solution

Solution using Topological Sorting. import java.io.*; import java.util.*; class Main  {     public static HashMap<Integer, ArrayList<Integer>> adjListOut = new HashMap<Integer, ArrayList<Integer>>();         public static void initAdjList(int numTasks) {         for (int i = 0; i < numTasks; i++) {             adjListOut.put((i+1), new ArrayList<Integer>());         }     }         public static void readDependencies(BufferedReader br, int[] numDependencies, int numRelations) throws NumberFormatException, IOException {         for (int i = 0; i < numRelations; i++) {             int dependency = reader(br);             int dependent = reader(br);                         adjListOut.get(dependency).add(dependent);             numDependencies[dependent]++;         }     }         public static void checkZeroDegree(int numTasks, int[] numDependencies, Queue<Integer> zeroDegree) {         for (int i = 0; i < numTasks; i++) {             if (num

(URI) Quadrado e ao Cubo - Solution

import java.io.*; class Main  {     public static void process() throws NumberFormatException, IOException {            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                         int num = Integer.parseInt(br.readLine());                 for (int i = 1; i <= num; i++) {             int pow2 = i*i;             int pow3 = pow2*i;             System.out.println(i + " " + pow2 + " " + pow3);         }                 return;     }         public static void main(String[] args) throws NumberFormatException, IOException {         Main m = new Main();         m.process();         System.exit(0);     } }

(URI) Resto da Divisão - Solution

import java.io.*; class Main  {     public static void process() throws NumberFormatException, IOException {            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));                         int num1 = Integer.parseInt(br.readLine());         int num2 = Integer.parseInt(br.readLine());                 if (num1 > num2) {             int tmp = num1;             num1 = num2;             num2 = tmp;           }                 for (int i = num1+1; i < num2; i++) {             if (i%5 == 2 || i%5 == 3) {                 System.out.println(i);             }         }                 return;     }         public static void main(String[] args) throws NumberFormatException, IOException {         Main m = new Main();         m.process();         System.exit(0);     } }

(UVA) The Forrest for the Trees - Solution

I used the Union-Find approach to solve this problem. First, I keep every edge in an ArrayList because I cannot call the union method while the letters are not related to a number. Then, when we read the list of letters (points) of the tree, we associate each letter to a number in order to use it in the union method. In the end, I return one array with two elements in the count method. The first position of my array corresponds to the number of trees in the case, and the second position corresponds to the number of "acorns" (nodes without any edge). import java.io.*; import java.util.*; class Main  {     public static HashMap<Character, Integer> map = new HashMap<Character, Integer>();     public static int[] nodeParent;     public static int[] depth;         public static int[] count() {         int[] v = new int[nodeParent.length+1];                 for (int i = 1; i < nodeParent.length; i++) {             v[root(nodeParent[i])] += 1 ;   

(URI) Dudu Faz Serviço - Solution 2

Solution using Topological Sorting to check for cycles in a graph.   import java.io.*; import java.util.*; class Main  {     public static HashMap<Integer, ArrayList<Integer>> adjListOut = new HashMap<Integer, ArrayList<Integer>>();          public static void printAnswer(BufferedWriter bw, int documentsVisited, int numDocuments) throws NumberFormatException, IOException {         if (documentsVisited != numDocuments) {             bw.write("SIM\n");         }         else {             bw.write("NAO\n");         }     }         public static int topoSort(Queue<Integer> zeroDegree, int[] dependencies) {         int documentsVisited = 0;         while (zeroDegree.size() > 0) {             int currDocument = zeroDegree.poll();             documentsVisited++;             for (int j = 0; j < adjListOut.get(currDocument).size(); j++) {                 int reachDocument = adjListOut.get(currDocument).get(j);   

(URI) Dudu Faz Serviço - Solution 1

Solution using Depth-First Search to look for cycles in a graph. import java.io.*; import java.util.*; class Main  {     public static HashMap<Integer, ArrayList<Integer>> adjList = new HashMap<Integer, ArrayList<Integer>>();          public static void printAnswer(BufferedWriter bw, boolean loop) throws NumberFormatException, IOException {         if (loop) {             bw.write("SIM\n");         }         else {             bw.write("NAO\n");         }     }         public static boolean dfs(int currNode, HashSet<Integer> visited, HashSet<Integer> current) {         boolean loop = false;                   visited.add(currNode);         current.add(currNode);                 ArrayList<Integer> reachables = adjList.get(currNode);         for (int i = 0; i < reachables.size() && !loop; i++) {             int node = reachables.get(i);             if (visited.contains(node) && current.contains(node)) {   

(SPOJ) Distância de Manhattan - Solution

import java.io.*; import java.util.*; import java.lang.*; class Main  {      public static void process() throws NumberFormatException, IOException {            Scanner sc = new Scanner(System.in);                 int mariaX = sc.nextInt();         int mariaY = sc.nextInt();         int meetingX = sc.nextInt();         int meetingY = sc.nextInt();                         System.out.println(Math.abs(mariaX-meetingX) + Math.abs(mariaY-meetingY));                 return;     }         public static void main(String[] args) throws NumberFormatException, IOException {         Main m = new Main();         m.process();         System.exit(0);     } }

(SPOJ) Orkut - Solution

You can check another solution for this problem here . In the previous solution, I used an adjacency matrix. Now, I used an adjacency list. Remember that the choice between using an adjacency matrix or an adjacency list depends on the problem. If the adjacency matrix is sparse, it is usually better to use an adjacency list. For both solutions, I used a Topological Sorting. You can find more about this topic here and here . import java.io.*; import java.util.*; class Main  {     public static HashMap<String, ArrayList<String>> adjListOut = new HashMap<String, ArrayList<String>>();         public static void printAnswer(ArrayList<String> seq, int numFriends) {         if (seq.size() == numFriends) {             for (int i = 0; i < numFriends-1; i++) {                          System.out.print(seq.get(i) + " ");             }             System.out.println(seq.get(numFriends-1));         }         else {             System.out.println(&qu

(UVA) My Dear Neighbours - Solution

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 static void printAnswer(int numNeighbors, int[] neighbors, int better) {         boolean firstTime = true;         for (int j = 1; j <= numNeighbors; j++) {             if (neighbors[j] == better) {                 if (!firstTime) {                     System.out.print(" ");                 }       

(URI) Feynman - Solution

Once we know that the entry is between 1 and N (N <= 100), we can find the result for every number between 1 and N and store it in an array. Then, for every entry, we only need to call for the array using the entry as the position (e.g.: v[entry]). import java.io.*; class Main  {     public static final int MAX = 100;         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 process() throws NumberF