Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- class Graph {
- private int V; // Количество вершин
- private List<Integer>[] adjList; // Список смежности
- public Graph(int vertices) {
- V = vertices;
- adjList = new ArrayList[vertices];
- for (int i = 0; i < vertices; ++i) {
- adjList[i] = new ArrayList<>();
- }
- }
- public void addEdge(int u, int v) {
- adjList[u].add(v);
- adjList[v].add(u);
- }
- public Set<Integer> findVertexCover() {
- Set<Integer> vertexCover = new HashSet<>();
- boolean[] visited = new boolean[V];
- for (int u = 0; u < V; u++) {
- if (!visited[u]) {
- for (int v : adjList[u]) {
- if (!visited[v]) {
- vertexCover.add(u);
- vertexCover.add(v);
- visited[u] = true;
- visited[v] = true;
- break;
- }
- }
- }
- }
- return vertexCover;
- }
- }
- public class Main {
- private static final int MIN_SIZE = 3;
- private static final int MAX_SIZE = 12;
- private static final int MIN_VALUE = 0;
- private static final Scanner scanner = new Scanner(System.in);
- public static void main(String[] args) throws FileNotFoundException {
- outputTaskInfo();
- processUserInput();
- scanner.close();
- }
- public static void outputTaskInfo() {
- System.out.println("Найти вершинное покрытие графа.");
- }
- public static void processUserInput() throws FileNotFoundException {
- int sizeVertices = 0;
- int choiceForInput;
- String pathToIn = "";
- System.out.println("Вы желаете ввести данные с консоли(0) или взять данные из файла(1)?");
- choiceForInput = getVerificationOfChoice();
- if (choiceForInput == 0) {
- sizeVertices = readSizeFromConsole();
- Graph graph = new Graph(sizeVertices);
- fillGraphFromConsole(graph, sizeVertices);
- processUserOutput(graph);
- }
- if (choiceForInput == 1) {
- pathToIn = inputPathToFile();
- sizeVertices = readSizeFromFile(pathToIn);
- Graph graph = new Graph(sizeVertices);
- fillGraphFromFile(graph, sizeVertices, pathToIn);
- processUserOutput(graph);
- }
- }
- public static void processUserOutput(Graph graph) {
- int choiceForOutput;
- String path = "";
- boolean isIncorrect;
- System.out.println("Вы желаете получить результат в консоли(0) или в файле(1)?");
- choiceForOutput = getVerificationOfChoice();
- Set<Integer> vertexCover = graph.findVertexCover();
- if (choiceForOutput == 1) {
- path = inputPathToFile();
- System.out.println("Вывод вершинного покрытия графа в файл...");
- do {
- isIncorrect = false;
- try {
- FileWriter writer = new FileWriter(path);
- writer.write("Вершинное покрытие графа:\n");
- for (int vertex : vertexCover) {
- writer.write(vertex +" ");
- }
- writer.close();
- } catch (IOException e) {
- isIncorrect = true;
- System.out.println("Ошибка! Измените параметры файла или укажите новую ссылку!");
- path = inputPathToFile();
- }
- } while (isIncorrect);
- System.out.println("Данные успешно записаны в файл!");
- }
- if (choiceForOutput == 0) {
- System.out.println("Вершинное покрытие графа:");
- for (int vertex : vertexCover) {
- System.out.print(vertex + " ");
- }
- }
- }
- public static int getVerificationOfChoice() {
- int choice = 0;
- boolean isIncorrect;
- do {
- isIncorrect = false;
- try {
- choice = Integer.parseInt(scanner.nextLine());
- } catch (NumberFormatException e) {
- System.out.println("Проверьте корректность ввода данных!");
- isIncorrect = true;
- }
- if (!isIncorrect && (choice != 0 && choice != 1)) {
- System.out.println("Для выбора введите 0 или 1!");
- isIncorrect = true;
- }
- } while (isIncorrect);
- return choice;
- }
- public static String inputPathToFile() {
- boolean isIncorrect;
- String path;
- System.out.println("Укажите путь к файлу: ");
- do {
- isIncorrect = false;
- path = scanner.nextLine();
- File file = new File(path);
- if (!file.exists()) {
- System.out.println("По указанному пути файл не найден! Укажите правильный путь: ");
- isIncorrect = true;
- }
- } while (isIncorrect);
- return path;
- }
- public static int readSizeFromConsole(){
- int size = 0;
- boolean isIncorrect;
- System.out.print("Введите количество вершин графа: ");
- do {
- isIncorrect = false;
- try {
- size = Integer.parseInt(scanner.nextLine());
- } catch (NumberFormatException e) {
- System.out.println("Проверьте корректность ввода данных!");
- isIncorrect = true;
- }
- if (!isIncorrect && (size < MIN_SIZE || size > MAX_SIZE)) {
- System.out.println("Введите число от " + MIN_SIZE + " до " + MAX_SIZE + "! \n");
- isIncorrect = true;
- }
- } while (isIncorrect);
- return size;
- }
- public static int readSizeFromFile(final String path) {
- int size;
- System.out.println("Происходит чтение количества вершин...");
- try (BufferedReader br = new BufferedReader(new FileReader(path))) {
- size = Integer.parseInt(br.readLine());
- } catch (Exception e) {
- System.out.println("Ошибка при считывании количества вершин из файла!Введите количество с консоли!");
- size = readSizeFromConsole();
- }
- return size;
- }
- public static Graph fillGraphFromFile (Graph graph, int size, final String path) throws FileNotFoundException {
- int num1 = 0;
- int num2 = 0;
- int count = 0 ;
- Scanner fr = new Scanner(new File(path));
- System.out.println("Чтение вершин ...");
- fr.nextLine();
- while (fr.hasNext()) {
- fr.next();
- count++;
- }
- fr.close();
- if (count > size * 2) {
- System.out.println("Ошибка при чтении! Введите с консоли!");
- fillGraphFromConsole(graph, size);
- } else {
- fr = new Scanner(new File(path));
- fr.nextLine();
- for (int i = 0; i < size; i++) {
- try {
- num1 = fr.nextInt();
- num2 = fr.nextInt();
- } catch (Exception e) {
- System.out.println("Ошибка при считывании вершин из файла!Введите вершины с консоли!");
- fillGraphFromConsole(graph, size);
- }
- if (num1 < MIN_VALUE || num1 > (size - 1) || num2 < MIN_VALUE || num2 > (size - 1)) {
- System.out.println("Ошибка при считывании вершин из файла! Введите вершины с консоли!");
- fillGraphFromConsole(graph, size);
- }
- }
- }
- return graph;
- }
- public static int getVertices(int i, int numVertices) {
- int number = 0;
- boolean isIncorrect;
- do {
- isIncorrect = false;
- System.out.print("Введите " + i + " вершину графа: ");
- try {
- number = Integer.parseInt(scanner.nextLine());
- } catch (NumberFormatException e) {
- System.out.println("Проверьте корректность ввода данных!");
- isIncorrect = true;
- }
- if (!isIncorrect && (number < MIN_VALUE || number > (numVertices - 1))) {
- System.out.println("Введите число от " + MIN_VALUE + " до " + (numVertices - 1) + "!");
- isIncorrect = true;
- }
- } while (isIncorrect);
- return number;
- }
- public static Graph fillGraphFromConsole(Graph graph, int amountVertices) {
- int num1, num2;
- System.out.println("Добавьте положение ребер между введенными двумя вершинами (первая вершина 0)");
- for (int i = 0; i < amountVertices; i++) {
- num1 = getVertices(1, amountVertices);
- num2 = getVertices(2, amountVertices);
- graph.addEdge(num1, num2);
- }
- return graph;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement