Cod sursa(job #1705655)

Utilizator fabian26Pintea Fabian fabian26 Data 20 mai 2016 21:34:33
Problema Sortare topologica Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 1.78 kb
import java.io.*;
import java.util.*;

public class Main {
	public static List<List<Integer>> edges;
	public static int[] color;
	
	public static void main(String[] args) {
		/*
		 * Enter your code here. Read input from STDIN. Print output to STDOUT.
		 * Your class should be named Solution.
		 */
		MiScanner input = new MiScanner();
		int N = input.nextInt();
		int M = input.nextInt();
		
		color = new int[N + 1];
		edges = new ArrayList<List<Integer>>();
		for(int i = 0; i < N; i++) {
			edges.add(new ArrayList<Integer>());
		}
		
		for(int i = 0; i < M; i++) {
			int u = input.nextInt();
			int v = input.nextInt();
			edges.get(u - 1).add(v);
			edges.get(v - 1).add(u);
		}
		
		topoSort(N);
	}
	
	public static void topoSort(int N) {
		for(int i = 1; i <= N; i++) {
			if(color[i] == 0) 
				explore(i);
		}
	}
	
	public static void explore(int i) {
		System.out.print(i + " ");
		color[i]++;
		List<Integer> vecini = edges.get(i - 1);
		for(Integer vecin : vecini) {
			if(color[vecin] == 0) 
				explore(vecin);
		}
		color[i]++;
	}
}

class MiScanner {
	BufferedReader br;
	StringTokenizer st;

	public MiScanner() {
		br = new BufferedReader(new InputStreamReader(System.in));
	}

	String next() {
		while (st == null || !st.hasMoreElements()) {
			try {
				st = new StringTokenizer(br.readLine());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return st.nextToken();
	}

	int nextInt() {
		return Integer.parseInt(next());
	}

	long nextLong() {
		return Long.parseLong(next());
	}

	double nextDouble() {
		return Double.parseDouble(next());
	}

	String nextLine() {
		String str = "";
		try {
			str = br.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}
}