Cod sursa(job #1705903)

Utilizator FlorentinaPetcuFlorentina Petcu FlorentinaPetcu Data 21 mai 2016 02:32:56
Problema Sortare topologica Scor 80
Compilator java Status done
Runda Arhiva educationala Marime 1.85 kb

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Stack;

class GraphS {
	int nodes;
	public Map<Integer, List<Integer>> adiacenta;

	public GraphS() {
		adiacenta = new HashMap<>();
	}

	public GraphS(int nodes, Map<Integer, List<Integer>> edges) {
		this.nodes = nodes;
		this.adiacenta = edges;
	}

	public void readData(String filename) throws IOException {
		Scanner input = new Scanner(new FileReader(filename));
		nodes = input.nextInt();
		int M = input.nextInt();

		for (int i = 1; i <= nodes; i++)
			adiacenta.put(i, new ArrayList<Integer>());

		int node1, node2;
		for (int i = 0; i < M; i++) {
			node1 = input.nextInt();
			node2 = input.nextInt();
			adiacenta.get(node1).add(node2);
		}
		input.close();
	}

}

public class Main {

	static Stack<Integer> path;
	static boolean[] visited;
	static int[] cul;

	public static void explorare(GraphS g, int u) {
		if (cul[u] != 0)
			return;

		cul[u] = 1;

		List<Integer> adj = g.adiacenta.get(u);
		for (int i = 0; i < adj.size(); i++) {

			explorare(g, adj.get(i));
		}
		cul[u] = 2;
		path.push(u);
	}

	public static void main(String[] args) throws IOException {
		GraphS g = new GraphS();

		g.readData("sortaret.in");

		visited = new boolean[g.nodes + 1];
		path = new Stack<>();
		cul = new int[g.nodes + 1];

		for (int i = 1; i <= g.nodes; i++) {
			if (cul[i] == 0)
				explorare(g, i);
		}
		// System.out.println(path.toString());
		BufferedWriter write = new BufferedWriter(new FileWriter(new File("sortaret.out")));
		while (!path.isEmpty())
			write.write(path.pop() + " ");

		write.close();
	}

}