using
System;
using
System.Collections.Generic;
class
GFG {
static
int
LeastWeightedSumPath(
int
n, List<List<
int
>> edges,
int
src,
int
dst,
int
K) {
var
graph =
new
Dictionary<
int
, List<Tuple<
int
,
int
>>>();
for
(
int
i = 0; i < edges.Count; i++) {
var
edge = edges[i];
if
(!graph.ContainsKey(edge[0])) {
graph[edge[0]] =
new
List<Tuple<
int
,
int
>>();
}
graph[edge[0]].Add(
new
Tuple<
int
,
int
>(edge[1], edge[2]));
}
var
pq =
new
SortedSet<Tuple<
int
,
int
,
int
>>(
Comparer<Tuple<
int
,
int
,
int
>>.Create((i1, i2) =>
i1.Item1.CompareTo(i2.Item1)));
var
costs =
new
int
[n, K + 2];
for
(
int
i = 0; i < n; i++) {
for
(
int
j = 0; j < K + 2; j++) {
costs[i, j] =
int
.MaxValue;
}
}
costs[src, K + 1] = 0;
pq.Add(
new
Tuple<
int
,
int
,
int
>(0, src, K + 1));
while
(pq.Count > 0) {
var
top = pq.Min;
pq.Remove(top);
if
(top.Item2 == dst) {
return
top.Item1;
}
if
(top.Item3 == 0) {
continue
;
}
if
(graph.ContainsKey(top.Item2)) {
foreach
(
var
neighbor
in
graph[top.Item2]) {
if
(costs[neighbor.Item1, top.Item3 - 1] < neighbor.Item2 + top.Item1) {
continue
;
}
costs[neighbor.Item1, top.Item3 - 1] = neighbor.Item2 + top.Item1;
pq.Add(
new
Tuple<
int
,
int
,
int
>(neighbor.Item2 + top.Item1, neighbor.Item1, top.Item3 - 1));
}
}
}
return
-1;
}
static
void
Main() {
int
n = 3, src = 0, dst = 2, k = 1;
var
edges =
new
List<List<
int
>>() {
new
List<
int
> { 0, 1, 100 },
new
List<
int
> { 1, 2, 100 },
new
List<
int
> { 0, 2, 500 }
};
Console.WriteLine(LeastWeightedSumPath(n, edges, src, dst, k));
}
}