import java.io.*; import java.util.*; import java.awt.geom.*; /** * Solution to Dueling Philosophers * * @author vanb */ public class duelingphilosophers { public Scanner sc; public PrintStream ps; public static final int MAXCOUNT = 1000000; /** * Driver. * @throws Exception */ public void doit() throws Exception { sc = new Scanner( System.in ); //new File( "duelingphilosophers.sample" ) ); ps = System.out; //new PrintStream( new FileOutputStream( "duelingphilosophers.out" ) ); // needs[i] is a count of all of the essays that define a term used in essay i. // In other words, it's a count of all the essays that essay i needs to come before it. int needs[] = new int[MAXCOUNT]; // feeds[i] is a count of all the essays that use a term defined in essay i. // In other words, it's a list of all the essays that essay i 'feeds' LinkedList feeds[] = new LinkedList[MAXCOUNT]; // Initialize the feeds for( int i=0; i(); } // This will be a list of all of the essays with 0 needs. // That means that they could come next in then ordering. LinkedList zeros = new LinkedList(); for(;;) { // There are n essays int n = sc.nextInt(); int m = sc.nextInt(); if( n==0 ) break; // Initialize the main structures for this new data set for( int i=0; i 1 ) { // If there's more than one essay with no needs, // then there's more than one solution. That's answer=2. // But, we can't bail out, in case we find a loop later. answer = 2; } // So, grab the next essay int essay = zeros.removeFirst(); // Look at all of the essays that this one feeds. // They now have one fewer need. for( int j : feeds[essay] ) { --needs[j]; if( needs[j]==0 ) { zeros.add( j ); } } } ps.println( answer ); } } /** * @param args */ public static void main( String[] args ) throws Exception { new duelingphilosophers().doit(); } }