Cod sursa(job #1430548)

Utilizator serbanalex2202Serban Alexandru serbanalex2202 Data 8 mai 2015 16:27:34
Problema Sortare topologica Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 2.67 kb
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;

class Nod {
	public int id;
	int cost = -1; // cost pana aici pentru bfs cand o muchie costa 1
	int timp; // timp de atingere
	public boolean viz;
	public ArrayList<Nod> vecini = new ArrayList<Nod>();

	// public ArrayList<Integer> costuri = new ArrayList<Integer>();

	public Nod(int id) {
		super();
		this.id = id + 1;
	}

	@Override
	public String toString() {
		return "" + this.id;
	}

}

public class Main {

	public static void main(String[] args) throws FileNotFoundException {
		ArrayList<Nod> g = new ArrayList<Nod>();
		readData(g);
		DFS(g);

		// afiG(g);
	}

	// TOPSORT
	public static LinkedList<Nod> DFS(ArrayList<Nod> g) throws FileNotFoundException {

		// cu lista nodurilor in ordinea timpului de incepere a vzitarii
		PrintWriter writer = new PrintWriter(new FileOutputStream("sortaret.out"));
		LinkedList<Nod> solutie = new LinkedList<Nod>();
		LinkedList<Nod> stiva = new LinkedList<Nod>();
		Nod curent;

		int timp = 0;

		// parcurgem toate nodurile din graf - pentru fiecare nod incercam DFS
		for (Nod nod : g) {

			// luam primul nod il punem in stiva
			if (nod.viz == false) {
				stiva.push(nod);
				nod.viz = true;
				nod.timp = timp++;
				solutie.add(nod);
				writer.write(String.valueOf(nod.id) + " ");

				// cat timp stiva nu e goala extrage nod scrie ca l-ai vizitat si pune in stiva
				// vecinii
				while (!stiva.isEmpty()) {
					// extragem primul nod din stiva si punem in stiva toti vecinii lui nevizitati

					curent = stiva.remove();

					for (Nod n : curent.vecini) {
						if (n.viz == false) {
							stiva.push(n);
							n.viz = true;
							n.timp = timp++;
							solutie.add(n);
							writer.write(String.valueOf(n.id) + " ");
						}
					}
				}
			}

		}

		writer.close();
		return solutie;

	}

	public static void readData(ArrayList<Nod> g) throws FileNotFoundException {
		int noduri;
		int muchii;

		Scanner s = new Scanner(new FileInputStream("sortaret.in"));

		noduri = s.nextInt();
		muchii = s.nextInt();

		for (int i = 0; i < noduri; i++) {

			g.add(new Nod(i));
		}

		for (int i = 0; i < muchii; i++) {
			int nod1 = s.nextInt() - 1;
			int nod2 = s.nextInt() - 1;
			g.get(nod1).vecini.add(g.get(nod2));

			// pentru neorientat
			// g.get(nod1).vecini.add(g.get(nod2));
		}

		s.close();
	}

	public static void afiG(ArrayList<Nod> g) {
		for (Nod nod : g) {
			System.out.print("id " + nod.id + " timp " + nod.timp + " : ");
			for (Nod n : nod.vecini) {
				System.out.print(n.id + " ");
			}
			System.out.println();
		}
	}
}