Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.strkk.other.graph.other;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.nio.file.Files;
- import java.nio.file.Paths;
- import java.time.Instant;
- import java.util.*;
- import java.util.Map.Entry;
- public class Planner {
- public static void main(String[] args) throws IOException {
- if(args.length < 1){
- System.out.println("Need a path to file, exit...");
- System.exit(1);
- }
- long start = Instant.now().getEpochSecond();
- Map<String, Node> map = new HashMap<>();
- try (BufferedReader br = Files.newBufferedReader(Paths.get(args[0]))) {
- String line = null;
- while ((line = br.readLine()) != null) {
- int i = line.indexOf(' ');
- String source = line.substring(0, i);
- String dest = line.substring(i + 1);
- Node s;
- if (map.containsKey(source)) {
- s = map.get(source);
- } else {
- s = new Node();
- map.put(source, s);
- }
- Node d;
- if (map.containsKey(dest)) {
- d = map.get(dest);
- } else {
- d = new Node();
- map.put(dest, d);
- }
- d.counter++;
- s.nodes.add(d);
- }
- }
- List<List<String>> result = new ArrayList<>();
- while (true) {
- List<String> list = new ArrayList<>();
- for (Iterator<Entry<String, Node>> it = map.entrySet().iterator(); it.hasNext(); ) {
- Entry<String, Node> e = it.next();
- Node value = e.getValue();
- if (!value.visited && value.counter == 0) {
- list.add(e.getKey());
- for (Node n : value.nodes) {
- n.counter--;
- n.visited = true;
- }
- it.remove();
- }
- }
- map.values().forEach(n -> n.visited = false);
- if (list.isEmpty()) {
- break;
- }
- result.add(list);
- }
- if (map.size() != 0) {
- throw new IllegalArgumentException("Tasks graph contains cycles!");
- }
- System.out.println((Instant.now().getEpochSecond() - start) + " seconds");
- // uncomment to see result
- // result.forEach(System.out::println);
- System.out.println("lists: " + result.size());
- }
- }
- class Node {
- int counter;
- List<Node> nodes = new ArrayList<>();
- boolean visited;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement