Under construction

Still being built. Things may change

Animal Companion in Maze

Time limit2sMemory limit512 MB

Summary
Given a directed room graph, find the longest walk where George never immediately reverses the door he just used, or report Infinite if he can walk forever.
Level

Medium7 of 10

Topics
Graph, Simulation, Greedy
Solved
No attempts yet

Problem

George, a pet monkey, has slipped his leash and escaped.

George is hopping around a maze-like building with many rooms. A door between two rooms leads straight into the adjacent room, not through a corridor. Some doors are one-way: they open from only one of their two sides.

George repeats picking at random a door he can open in the room he is in and moving through it into the next room. He believes that his owner is right behind him, so he never goes straight back through the door he just came through. If another door leads to the room he has just left, he may pick that door and go back.

Once the only door he can open is the one he came through, George is confined in that room and is caught there.

You know how the rooms of the building are connected by doors, but you do not know which room George is in right now.

Moving to an adjacent room through one door takes one unit of time.

Write a program that computes the longest time that can pass before George is confined in a room. Consider every room he might have started in and every choice of doors he might make.

Depending on how the rooms are organized, George may be able to keep hopping around forever without being caught.

Doors may be on the ceilings or the floors of rooms, so the connections between rooms may not be drawable as a planar graph.

Input

The input consists of a single test case in the following format.

n m
x1 y1 w1
.
.
.
xm ym wm

The first line has two integers nn and mm, the number of rooms and the number of doors (2≤n≤1000002 \le n \le 100000, 1≤m≤1000001 \le m \le 100000). Each of the next mm lines describes one door. The ii-th of them has three integers xix_i, yiy_i and wiw_i (1≤xi≤n1 \le x_i \le n, 1≤yi≤n1 \le y_i \le n, xi≠yix_i \ne y_i, wi=1w_i = 1 or wi=2w_i = 2). Door ii connects rooms xix_i and yiy_i. If wi=1w_i = 1, the door is one-way from xix_i to yiy_i. If wi=2w_i = 2, it can be used in both directions. Several doors may connect the same pair of rooms.

Output

Print the maximum number of time units after which George is confined in a room. If George can keep hopping around forever, print Infinite.

Examples4

  1. Example 1

    Input
    2 1
    1 2 2
    
    Expected output
    1
    
  2. Example 2

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

    Input
    6 7
    1 3 2
    3 2 1
    3 5 1
    3 6 2
    4 3 1
    4 6 1
    5 2 1
    
    Expected output
    4
    
  4. Example 4

    Input
    3 2
    1 3 1
    1 3 1
    
    Expected output
    1