Pagini recente » Cod sursa (job #1241124) | Cod sursa (job #2274630) | Cod sursa (job #2458001) | Cod sursa (job #2671855) | Cod sursa (job #1264637)
package graphs;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class Euler {
protected class Edge {
private int u;
private int v;
private boolean used;
protected Edge(int u, int v) {
this.u = u;
this.v = v;
used = false;
}
protected void use() {
this.used = true;
}
protected boolean isUsed() {
return used;
}
protected int getU() {
return u;
}
protected int getV() {
return v;
}
}
private Scanner sc;
private PrintWriter pw;
private static ArrayList<Integer>[] graph;
private static ArrayList<Edge> edges;
private static ArrayList<Integer> solution;
public Euler() throws FileNotFoundException {
edges = new ArrayList<Edge>();
solution = new ArrayList<Integer>();
pw = new PrintWriter(new File("ciclueuluer.out"));
readData();
parseGraph(0);
if (solution.size() == edges.size()) {
for(int v : solution) {
pw.print((v + 1) + " ");
}
} else {
pw.println("-1");
}
pw.close();
}
@SuppressWarnings("unchecked")
private void readData() {
try {
sc = new Scanner(new File("ciclueuluer.in"));
graph = new ArrayList[sc.nextInt()];
int vertexs = sc.nextInt();
for (int i = 0; i < vertexs; i++) {
int vertex1 = sc.nextInt() - 1;
int vertex2 = sc.nextInt() - 1;
if (graph[vertex1] == null) {
graph[vertex1] = new ArrayList<Integer>();
}
if (graph[vertex2] == null) {
graph[vertex2] = new ArrayList<Integer>();
}
edges.add(new Edge(vertex1, vertex2));
if (!graph[vertex1].contains(vertex2)) {
graph[vertex1].add(vertex2);
}
if (!graph[vertex2].contains(vertex1)) {
graph[vertex2].add(vertex1);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
sc.close();
}
}
public static Edge returnEdge(int u, int v) {
for(Edge edge : edges) {
if (edge.getU() == u && edge.getV() == v) {
return edge;
}
}
return null;
}
private static void parseGraph(int vertex) {
solution.add(vertex);
for(int adj : graph[vertex]) {
Edge edge = returnEdge(vertex, adj);
if (edge != null && !edge.isUsed()) {
edge.use();
parseGraph(adj);
}
}
}
public static void main(String args[]) {
try {
new Euler();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}