#C6096. Connecting Villages Within Budget
Connecting Villages Within Budget
Connecting Villages Within Budget
You are given N villages and M possible roads connecting them. Each road connects two villages with a given length. You are also provided a budget B. Your task is to determine whether it is possible to connect all the villages (i.e. form a spanning tree) using some of the given roads such that the total length (cost) does not exceed the budget.
In other words, let \(T\) be a set of roads that connects all the villages. Then the condition to satisfy is:
[ \sum_{e \in T} \text{length}(e) \leq B ]
If such a set \(T\) exists, print YES
; otherwise, print NO
.
You are expected to use a Minimum Spanning Tree (MST) algorithm (such as Kruskal's or Prim's algorithm) with a Disjoint Set Union (Union-Find) to solve this problem.
inputFormat
The input is read from stdin and is formatted as follows:
- The first line contains three integers
N
,M
, andB
whereN
is the number of villages,M
is the number of roads, andB
is the budget. - The following
M
lines each contain three space‑separated integersu
,v
, andl
, representing a road connecting villageu
and villagev
with a length (cost)l
.
Villages are numbered from 1 to N.
outputFormat
The output is written to stdout and should be a single line containing either YES
if it is possible to connect all villages within the budget, or NO
otherwise.
5 7 15
1 2 3
1 3 4
2 3 1
2 4 2
3 4 5
3 5 6
4 5 1
YES