#K14961. Minimum Direct Connections

    ID: 24251 Type: Default 1000ms 256MiB

Minimum Direct Connections

Minimum Direct Connections

Given a set of computers numbered from 1 to \(n\) and a set of potential direct connections between them, your task is to determine the minimum number of connections needed to ensure that every computer is connected in a single network. A connection between computers \(a\) and \(b\) is only possible if the distance \(d\) between them satisfies \(d \leq r\), where \(r\) is the maximum allowed connection range.

If it is impossible to connect all computers within the distance constraint, output \(-1\). Otherwise, output the number of connections required (which is \(n-1\) if a spanning tree exists).

You may approach this problem by constructing a graph with only the eligible connections and then finding a minimum spanning tree (MST) using algorithms such as Prim's or Kruskal's. Ensure that all computers are visited; if not, the network cannot be fully connected under the given constraints.

inputFormat

The input is read from standard input (stdin) and follows this format:

  • The first line contains two integers \(n\) and \(r\), where \(n\) is the number of computers and \(r\) is the maximum allowed distance for a direct connection.
  • The second line contains an integer \(m\), which represents the number of potential connections available.
  • Each of the following \(m\) lines contains three space-separated integers \(a\), \(b\), and \(d\), indicating that there is a connection between computer \(a\) and computer \(b\) with distance \(d\).

Note: The computers are numbered from 1 to \(n\).

outputFormat

Output to standard output (stdout) a single integer representing the minimum number of direct connections required to connect all computers. If it is impossible to connect all computers under the given constraints, output \(-1\).

## sample
5 10
7
1 2 5
1 3 12
2 3 7
2 4 3
3 4 6
3 5 15
4 5 4
4

</p>