All problems

Problem 939

Remove Max Number of Edges to Keep Graph Fully Traversable

Hard · 30 pts · Graph, Union Find

Problem

An undirected graph has N nodes and three kinds of edges: type 1 can be used only by Alice, type 2 only by Bob, and type 3 by both. Remove as many edges as possible while both Alice and Bob can still travel between every pair of nodes using their own usable edges. Print the maximum number of removable edges, or -1 if the graph is not fully traversable for both even with all edges. Add type 3 edges first to both union-find structures, then the private ones; every edge that joins nothing new is removable.

Input

The first line contains N and M. Each of the next M lines contains TYPE, u and v (nodes are numbered from 1).

Output

Print the maximum number of removable edges, or -1.

Constraints

1 <= N <= 100000; 1 <= M <= 100000; 1 <= TYPE <= 3; u != v; no two edges are identical

Example input

4 6
3 1 2
3 2 3
1 1 3
1 2 4
1 1 2
2 3 4

Example output

2

Explanation

With 4 nodes and edges (3,1,2), (3,2,3), (1,1,3), (1,2,4), (1,1,2), (2,3,4): the two shared edges plus one Alice edge (2,4) and one Bob edge (3,4) keep both connected. The edges (1,1,3) and (1,1,2) are not needed, so the answer is 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Shortest Path to Get All Keys Next: Number of Good Paths