(UVA) Pick Up Sticks - Solution

I used Topological Sorting to solve this problem.


import java.io.*;
import java.util.*;

class Main  {
    public static HashMap<Integer, ArrayList<Integer>> adjListOut;
    public static int[] degrees;
   
    public static ArrayList<Integer> topoSort(int numSticks) {
        Queue<Integer> zeroDegree = new ArrayDeque<Integer>();
        for (int i = 1; i <= numSticks; i++) {
            if (degrees[i] == 0) {
                zeroDegree.add(i);
            }
        }
       
        ArrayList<Integer> seq = new ArrayList<Integer>();
        while (zeroDegree.size() > 0) {
            int currStick = zeroDegree.poll();
            seq.add(currStick);
            ArrayList<Integer> reachSticks = adjListOut.get(currStick);
            for (int i = 0; i < reachSticks.size(); i++) {
                degrees[reachSticks.get(i)]--;
                if (degrees[reachSticks.get(i)] == 0) {
                    zeroDegree.add(reachSticks.get(i));
                }
            }
        }
       
        return seq;
    }
   
    public static void process() throws NumberFormatException, IOException {  
        Scanner sc = new Scanner(System.in);
       
        int numSticks = sc.nextInt();
        int numDependencies = sc.nextInt();
        while (numSticks != 0 && numDependencies != 0) {
            adjListOut = new HashMap<Integer, ArrayList<Integer>>();
            for (int i = 1; i <= numSticks; i++) {
                adjListOut.put(i, new ArrayList<Integer>());
            }
           
            degrees = new int[numSticks+1];
            for (int i = 0; i < numDependencies; i++) {
                int s1 = sc.nextInt();
                int s2 = sc.nextInt();
                adjListOut.get(s1).add(s2);
                degrees[s2]++;
            }
           
            ArrayList<Integer> seq = topoSort(numSticks);
           
            if (seq.size() != numSticks) {
                System.out.println("IMPOSSIBLE");
            }
            else {
                for (int i = 0; i < seq.size(); i++) {
                    System.out.println(seq.get(i));
                }
            }
           
            numSticks = sc.nextInt();
            numDependencies = sc.nextInt();
        }
                                                
        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) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução