(UVA) Start Grid - Solution 2

If you want to see another solution for this problem, click here.

I used Bubble Sort to solve this problem.



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 process() throws NumberFormatException, IOException {  
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       
        String line = br.readLine();
        while (line != null) {
            int numCompetitors = Integer.parseInt(line);
           
            ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
            for (int i = 0; i <= numCompetitors; i++) {
                list.add(i, new ArrayList<Integer>());
            }
           
            int[] startingGrid = new int[numCompetitors+1];
            for (int i = 1; i <= numCompetitors; i++) {
                startingGrid[i] = reader(br);
            }

            int[] finishingGrid = new int[numCompetitors+1];
            for (int i = 1; i <= numCompetitors; i++) {
                finishingGrid[reader(br)] = i;
            }
            // array based on positions in finishingGrid
            int[] newStartingGrid = new int[numCompetitors+1];
            for (int i = 1; i <= numCompetitors; i++) {
                int competitorID = startingGrid[i];
                newStartingGrid[i] = finishingGrid[competitorID];
            }
           
            int changes = 0;
            for (int i = 1; i <= numCompetitors; i++) {
                for (int j = 1; j < numCompetitors; j++) {
                    if (newStartingGrid[j] > newStartingGrid[j+1]) {
                        int tmp = newStartingGrid[j];
                        newStartingGrid[j] = newStartingGrid[j+1];
                        newStartingGrid[j+1] = tmp;
                       
                        changes++;
                    }
                }
            }
           
            System.out.println(changes);
           
            line = br.readLine();
        }
                   
        return;
    }
  
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();

        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução