import java.util.*; public class JohnChecker { public static final int MMAX_CHAP = 1000; public static final int MAX_LEN = 1000; public static int exitCode = 42; public static void printError(int line, String msg) { System.out.println("ERROR Line " + line + ": " + msg); exitCode = -1; } public static void checkIntBounds(int x, int min, int max, String name, int nLines) { if (x < min || x > max) printError(nLines, "invalid " + name + " value: " + x); } public static void checkCharBounds(char x, char min, char max, String name, int nLines) { if (x < min || x > max) printError(nLines, "invalid " + name + " value: " + x); } public static void checkDoubleBounds(double x, double min, double max, String name, int nLines) { if (x < min || x > max) printError(nLines, "invalid " + name + " value: " + x); } public static int nextInt(StringTokenizer st) { return Integer.parseInt(st.nextToken()); } public static void main(String [] args) { Scanner in = new Scanner(System.in); int n, m; String line; int nLines=0; line = in.nextLine(); nLines++; StringTokenizer st = new StringTokenizer(line); if (st.countTokens() != 2) printError(nLines, "number of values on line incorrect"); n = nextInt(st); m = nextInt(st); checkIntBounds(n, 2, MMAX_CHAP, "n", nLines); checkIntBounds(m, 0, n-1, "m", nLines); int numvals = 0; while (in.hasNextLine() && numvals < n) { line = in.nextLine(); nLines++; st = new StringTokenizer(line); numvals += st.countTokens(); for(int i=0; i childlist = new ArrayList<>(); ArrayList parentlist = new ArrayList<>(); int [] childlist = new int[n+1]; for(int i=1; i<=n; i++) childlist[i] = -1; boolean loopFound = false; while (in.hasNextLine()) { line = in.nextLine(); nLines++; if (++numvals > m) { printError(nLines, "too many lines"); break; } st = new StringTokenizer(line); if (st.countTokens() != 2) printError(nLines, "incorrect number of values"); int p = nextInt(st); int c = nextInt(st); checkIntBounds(p, 1, n, "parent chapter", nLines); checkIntBounds(c, 1, n, "parent chapter", nLines); if (p == c) printError(nLines, "parent and child chapters identical"); if (p > c) printError(nLines, "parent > child"); parentlist.add(p); if (childlist[c] != -1) printError(nLines, "chapter " + c + " appears more than once as a child"); childlist[c] = p; if (!loopFound) { int i=p; while (i != -1 && i != c) i = childlist[i]; if (i == c) { printError(nLines, "dependency loop found starting with " + c); loopFound = true; } } } int count = 0; for(int c : childlist) { if (!parentlist.contains(c)) count++; } if (count < 2 && (n-m) < 2) printError(nLines, "less than two chapters with no prerequisites"); // int numTrees = 0; // for(int i=1; i<=n; i++) // if (childlist[i] == -1) // numTrees++; // System.out.println("number of trees = " + numTrees); System.exit(exitCode); } }