Pagini recente » Cod sursa (job #780703) | Cod sursa (job #633447) | Cod sursa (job #1043187) | Cod sursa (job #2112806) | Cod sursa (job #1431094)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
public class Main {
Node[] graph;
int nodesCount;
int edgesCount;
int source;
int[] distance;
Color[] color;
int[] parent;
Stack<Integer> topSort = new Stack<Integer>();
int time = 0;
public static enum Color {
WHITE,GREY,BLACK;
}
public class Node {
int a, b;
int discTime = 0;
int finTime = 0;
List<Integer> neighbors = new LinkedList<Integer>();
public Node(int a, int b) {
this.a = a;
this.b = b;
}
public void addNeighbor(int u) {
this.neighbors.add(u);
}
public List<Integer> getNeighbors() {
return neighbors;
}
}
public void init() {
for (int u = 0; u < nodesCount; u++) {
parent[u] = -1;
color[u] = Color.WHITE;
}
for (int u = 0; u < nodesCount; u++) {
if (color[u] == Color.WHITE) {
dfs(u);
}
}
}
public void dfs(int u) {
//graph[u].discTime = time++;
color[u] = Color.GREY;
for (int v : graph[u].getNeighbors()) {
if (color[v] == Color.WHITE) {
//parent[v] = u;
dfs(v);
}
}
//graph[u].finTime = time++;
color[u] = Color.BLACK;
topSort.add(u);
}
public void writeData() {
PrintWriter out = null;
try {
out = new PrintWriter("sortaret.out");
while (!topSort.isEmpty()) {
int u = topSort.pop() + 1;
out.write(u + " ");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (out != null ){
out.close();
}
}
}
public void readData() {
BufferedReader in;
try {
in = new BufferedReader(new FileReader("sortaret.in"));
String line = in.readLine();
String[] tokens = line.split(" ");
nodesCount = Integer.valueOf(tokens[0]);
edgesCount = Integer.valueOf(tokens[1]);
graph = new Node[nodesCount];
for (int i = 0; i < nodesCount; i++) {
graph[i] = new Node(0, 0);
}
parent = new int[nodesCount];
color = new Color[nodesCount];
distance = new int[nodesCount];
for (int i = 0; i < edgesCount; i++) {
line = in.readLine();
System.out.println(line);
tokens = line.split(" ");
int first = Integer.valueOf(tokens[0]) - 1;
int second = Integer.valueOf(tokens[1]) - 1;
graph[first].addNeighbor(second);
}
printGraph();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void printGraph() {
for (int u = 0; u < nodesCount; u++) {
System.out.println(u);
for (int v : graph[u].getNeighbors()) {
System.out.print(v + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Main problem = new Main();
problem.readData();
problem.init();
problem.writeData();
}
}