Pipe Down
Mario has been tasked with maintaining a network of green underground pipes in the Mushroom Kingdom, but he has encountered a significant issue. The pipe network is made up of ports and pipes that connect them. Some pipes have flow regulators, meaning water can only flow one way through that pipe, while some do not and will allow water to pass both ways. However, Mario has learnt that these undirected pipes are impeding the efficiency of the system as they can lead to blockages and deadlocks. Mario has been tasked with installing flow regulators into each of the undirected pipes so that they only allow directional flow, and he can choose either direction when installing the regulators.
However, Mario wants to be able to direct water from inlets at any of the ports to outlets at and of the other ports, so the pipe network must be strongly connected. Every port in the network must be reachable from every other port in the network by only traversing the pipes which are now all directional.
It is guaranteed that the pipe network will initially be strongly connected, but Mario wants to know if it is possible to make the network more efficient by installing flow regulators, while having it still be strongly connected. Each undirected pipe has to be fixed using a flow regulator so water only flows in a single direction. However, it is possible for ports to have multiple pipes between them.
Input
The first line contains two integers and
— the number of ports and the number of pipes. The ports are labelled
through
.
The next lines describe the pipes. Each line contains
,
, and
, where
and
are the endpoints of the pipe (
), and
is the type. If
is
, the pipe is undirected, so water can flow both ways. If
is
, the pipe has an existing flow regulator, so water can only flow from port
towards
.
Output
Output YES
if it is possible to assign directions to all undirected pipes while keeping the network strongly connected. Otherwise, output NO
.
Example
Input 1
4 4
1 2 1
2 3 0
3 4 0
4 1 1
Output 1
YES
The only undirected pipes are and
. If we fix
and
then strong connectivity will be maintained as a sort of square will form, connected in a cycle.
Input 2
3 3
1 2 1
2 1 0
2 3 0
Output 2
NO
There is no way we can maintain strong connectivity here, as will only ever be reachable via a
-directional pipe.
Comments