Pagini recente » Cod sursa (job #2877251) | Cod sursa (job #1431089)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
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; // TODO ATENTI aici era +1 inainte
}
@Override
public String toString() {
return "" + this.id;
}
}
public class Main {
public static int timp, nr_ctc;
// public static ArrayList<ArrayList<Nod>> ctcuri = new ArrayList<ArrayList<Nod>>();
// public static LinkedList<Nod> s = new LinkedList<Nod>();
public static void main(String[] args) throws FileNotFoundException {
PrintWriter writer = new PrintWriter(new FileOutputStream("sortaret.out"));
ArrayList<Nod> g = new ArrayList<Nod>();
readData(g);
for (Nod nod : g) {
if (nod.viz == false) {
writer.write(String.valueOf(nod.id + 1) + " ");
nod.viz = true;
DFS(g, nod, writer);
}
}
writer.close();
// afiG(g);
}
// topsort recursiv
public static void DFS(ArrayList<Nod> g, Nod curent, PrintWriter writer)
throws FileNotFoundException {
// parcurgem toate nodurile din graf - pentru fiecare nod incercam DFS
for (Nod vecin : curent.vecini) {
if (vecin.viz == false) {
vecin.viz = true;
vecin.timp = ++timp;
writer.write(String.valueOf(vecin.id + 1) + " ");
DFS(g, vecin, writer);
}
}
}
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();
}
}
public static void sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}