Under construction

Still being built. Things may change

Come and Go

Interview

Time limit2sMemory limit512 MB

Summary
Given a mixed graph of one-way and two-way streets, decide whether every pair of intersections is mutually reachable.
Level

Medium6 of 10

Topics
Graph, DFS, Union-find
Solved
No attempts yet

Problem

A city has NN intersections joined by one-way streets and two-way streets. Many of the streets run through tunnels or over viaducts.

The road network must allow a round trip between any two intersections: for any intersections VV and WW, it must be possible to travel from VV to WW and from WW to VV.

Read the description of a city's road network and decide whether that requirement holds.

Input

The input contains several test cases. The first line of a test case has two integers NN and MM separated by a single space, the number of intersections and the number of streets (2≤N≤20002 \le N \le 2000, 2≤M≤N(N−1)/22 \le M \le N(N-1)/2). Each of the next MM lines describes one street with three integers VV, WW and PP, separated by single spaces. VV and WW are distinct intersection numbers (1≤V,W≤N1 \le V, W \le N, V≠WV \ne W), and PP is 1 or 2. If PP is 1, the street is one-way and runs from VV to WW. If PP is 2, the street connects VV and WW in both directions. No two streets connect the same pair of intersections.

The last test case is followed by a line containing two zeros separated by a single space. Do not process that line.

Output

For each test case, print one line with an integer GG. GG is 1 if the connectivity requirement holds, and 0 otherwise.

Examples4

  1. Example 1

    Input
    4 5
    1 2 1
    1 3 2
    2 4 1
    3 4 1
    4 1 2
    3 2
    1 2 2
    1 3 2
    3 2
    1 2 2
    1 3 1
    4 2
    1 2 2
    3 4 2
    0 0
    
    Expected output
    1
    1
    0
    0
    
  2. Example 2

    Input
    3 3
    1 2 1
    2 3 1
    3 1 1
    0 0
    
    Expected output
    1
    
  3. Example 3

    Input
    3 3
    1 2 1
    2 3 1
    1 3 1
    0 0
    
    Expected output
    0
    
  4. Example 4

    Input
    6 6
    1 2 1
    2 3 1
    3 1 1
    4 5 1
    5 6 1
    6 4 1
    0 0
    
    Expected output
    0