Remove Max Number Of Edges To Keep Graph Fully Traversable

hard
Alice and Bob have an undirected graph of n nodes and 3 types of edges:

Type 1: Can be traversed by Alice only.
Type 2: Can be traversed by Bob only.
Type 3: Can by traversed by both Alice and Bob.

Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.
Return the maximum number of edges you can remove, or return -1 if it's impossible for the graph to be fully traversed by Alice and Bob.

Input Format

First line contains two integers n and m. Each of next n lines contain 3 numbers denoting type of edges and the node between which node is placed.

Output Format

Print the maximum number of edges you can remove.

Constraints

1<= n <= 1000
1 <= edges.length <=  n * (n-1) / 2
1 <= edges[i][0] <= 3
1 <= edges[i][1] < edges[i][2] <= n
All tuples (typei, ui, vi) are distinct.

Example

Input
4 6
3 1 2
3 2 3
1 1 3
1 2 4
1 1 2
2 3 4
Output
2
Previous
Minimum Number Of Swaps Required To Sort An Array
Next
Swim In Rising Water

Related Questions