Skip to content
BytePatterns

Spare Roads for Two Travellers

HardUnion-Find#union-find#greedy~45m

Problem

A region has n towns numbered 1 to n and a list of roads [kind, u, v]. A road of kind 1 may be used only by the cyclist, kind 2 only by the driver, and kind 3 by both. The council wants to close as many roads as possible while each traveller can still get from every town to every other town using the roads open to them. Return the largest number of roads that can be closed, or -1 if even the full network fails one of the travellers.

Examples

Input:  n = 4, roads = [[3, 1, 2], [3, 2, 3], [1, 1, 3], [1, 2, 4], [1, 1, 2], [2, 3, 4]]
Output: 2
Why:    [1, 1, 2] and [1, 1, 3] duplicate links the shared roads already give the cyclist
Input:  n = 4, roads = [[3, 1, 2], [3, 2, 3], [1, 1, 4], [2, 1, 4]]
Output: 0
Why:    every road is needed by at least one traveller
Input:  n = 4, roads = [[3, 2, 3], [1, 1, 2], [2, 3, 4]]
Output: -1
Why:    edge case, the cyclist can never reach town 4 and the driver never town 1

Hints

0 / 3

Stuck on the idea rather than the code? Components & Cycles covers it.