Cod sursa(job #1369286)

Utilizator stefan.vascoVanea Stefan Vascocenco stefan.vasco Data 2 martie 2015 23:21:41
Problema Sortare topologica Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 2.59 kb
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;

class Sortp {

    private HashMap<Integer, LinkedList<Integer>> graph;
    private HashMap<Integer, Integer> indeg;

    public Sortp() {
        graph = new HashMap<Integer, LinkedList<Integer>>();
        indeg = new HashMap<Integer, Integer>();
    }

    public void addEdge(int nodeA, int nodeB) {
        if (!graph.containsKey(nodeA)) {
            graph.put(nodeA, new LinkedList<Integer>());
            indeg.put(nodeA, 0);
        }

        if (!graph.containsKey(nodeB)) {
            graph.put(nodeB, new LinkedList<Integer>());
            indeg.put(nodeB, 0);
        }

        graph.get(nodeA).add(nodeB);
        indeg.put(nodeB, indeg.get(nodeB) + 1);

    }


    public LinkedList<Integer> execDFSSort() {
        LinkedList<Integer> sorted = new LinkedList<Integer>();
        LinkedList<Integer> visited = new LinkedList<Integer>();

        for (Map.Entry<Integer, LinkedList<Integer>> node : graph.entrySet()) {
            if (!visited.contains(node.getKey())) {
                DFS(node.getKey(), sorted, visited);
            }
        }

        return sorted;
    }

    private void DFS(int currentNode, LinkedList<Integer> sorted, LinkedList<Integer> visited) {
        sorted.add(currentNode);
        visited.add(currentNode);
        for (int inNode : graph.get(currentNode)) {
            if (!visited.contains(inNode)) {
                DFS(inNode, sorted, visited);
            }
        }
    }

}

public class Main {

    private static void writeOutput(LinkedList<Integer> topsort) {
        try {
            PrintWriter pr = new PrintWriter("sortaret.out");
            for (int vertex : topsort) {
                pr.write(vertex + " ");
            }
            pr.println();
            pr.flush();
            pr.close();

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }

    }

    public static void main(String[] args) throws FileNotFoundException {
        Sortp sortp = new Sortp();
        try (Scanner sc = new Scanner(new FileInputStream("sortaret.in"))) {
            int vertexCount = sc.nextInt();
            int edgeCount = sc.nextInt();

            for (; edgeCount > 0; edgeCount--) {
                sortp.addEdge(sc.nextInt(), sc.nextInt());
            }
            sc.close();
        }
        writeOutput(sortp.execDFSSort());

    }

}