#K72717. Connected Graph with Exact Weight
Connected Graph with Exact Weight
Connected Graph with Exact Weight
You are given an undirected graph with n vertices and m edges. Each edge has a weight. The task is to determine whether it is possible to select a nonempty subset of the edges such that:
- The sum of the weights of the selected edges is exactly equal to W.
- The selected edges form a connected subgraph that spans all n vertices.
Formally, for a given graph \(G = (V, E)\) with \(|V| = n\) and a list of weighted edges, decide if there exists a subset \(E' \subseteq E\) satisfying:
- \(\sum_{e \in E'} w(e) = W\)
- The graph \(G' = (V, E')\) is connected (i.e. every vertex is reachable from every other vertex).
If such a subset exists, output "Yes"; otherwise, output "No".
Note: If there are no edges (i.e. \(m=0\)) then the answer is "No" even if \(n=1\), since a nonempty subset is required.
inputFormat
The input is given via standard input (stdin) in the following format:
< n > < m > < W > u1 v1 w1 u2 v2 w2 ... um vm wm
Where:
n
is the number of vertices.m
is the number of edges.W
is the required sum of weights.- Each of the following
m
lines contains three integers \(u_i\), \(v_i\), and \(w_i\) representing an edge between vertices \(u_i\) and \(v_i\) with weight \(w_i\).
outputFormat
Output a single line to standard output (stdout) containing either "Yes" if there exists a subset of edges meeting the conditions, or "No" otherwise.
## sample5 6 10
1 2 3
1 3 2
2 4 4
3 4 1
4 5 2
3 5 1
Yes