Dueling Philosophers

Given directed edges meaning essay d must precede essay u, decide whether the ordering is impossible, unique, or has multiple solutions.

Medium6GraphTopological sortImplementationQueueNo attempts yetTime limit2sMemory limit512 MB

Problem

After a sad and strange incident involving a room full of philosophers, several plates of spaghetti, and one fork too few, the faculty of the Department of Philosophy at ACM University has been going through the papers of a colleague who died recently. The faculty members were amazed to find a large number of unpublished essays. They believe that the essays, collected into one volume, are a major work of scholarship that will bring the department the positive publicity it badly needs. Every faculty member began to compete for the honor, and the fame, of editing the collection.

After much debate, the list of candidates is down to two. Both applicants were asked to explain how they would arrange the essays inside the final book. Both noted that many essays define terminology and concepts that other essays explore, and both agreed on the basic principle that an essay which uses a term must appear after the essay that defines that term. One candidate has presented what he claims is the only possible arrangement under those constraints, and argues that he should get the job because he has already done this major part of the work. The second candidate scoffs at that claim. He insists that many arrangements are possible, and that picking the best one needs an editor of true skill, meaning himself.

Write a program that decides whether zero, exactly one, or more than one arrangement of the essays is possible.

Input

The input holds several test cases. Each test case begins with a line containing two integers nn and mm separated by one space (1n10001 \le n \le 1000, 1m5000001 \le m \le 500000), where nn is the number of essays and mm is the number of relationships between essays caused by shared terms. Each of the next mm lines contains two integers dd and uu separated by one space (1d,un1 \le d, u \le n, dud \ne u), meaning that some term is defined in essay dd and used in essay uu. The input ends with a line containing two zeros.

Output

For each test case, print 0 if no arrangement is possible, 1 if exactly one arrangement is possible, or 2 if more than one arrangement is possible. Print 2 however many arrangements there are. Print no extra spaces, and do not separate the answers with blank lines.