using
System;
using
System.Collections.Generic;
class
GFG
{
static
void
DfsAll(
int
n,
int
s,
int
d, List<List<Tuple<
int
,
int
>>> graph,
bool
[] vis, List<List<
int
>> edgePath, List<
int
> tempEdge)
{
if
(s == d)
{
edgePath.Add(
new
List<
int
>(tempEdge));
return
;
}
vis[s] =
true
;
int
edgesInA = graph[s].Count;
for
(
int
i = 0; i < edgesInA; i++)
{
if
(!vis[graph[s][i].Item1])
{
tempEdge.Add(graph[s][i].Item2);
DfsAll(n, graph[s][i].Item1, d, graph, vis, edgePath, tempEdge);
tempEdge.RemoveAt(tempEdge.Count - 1);
}
}
vis[s] =
false
;
}
static
int
GetDistance(List<List<
int
>> edgePath,
int
k)
{
int
shortestDistance =
int
.MaxValue;
if
(edgePath.Count == 0)
return
-1;
foreach
(
var
x
in
edgePath)
{
if
(k == x.Count)
return
0;
SortedSet<
int
> minHeap =
new
SortedSet<
int
>();
int
sum = 0;
int
kSum = 0;
for
(
int
i = 0; i < x.Count; i++)
{
sum += x[i];
kSum += x[i];
minHeap.Add(x[i]);
if
(minHeap.Count > k)
{
kSum -= minHeap.Min;
minHeap.Remove(minHeap.Min);
}
}
shortestDistance = Math.Min(sum - kSum, shortestDistance);
}
return
shortestDistance;
}
static
int
Solve(List<List<Tuple<
int
,
int
>>> graph,
int
n,
int
k,
int
src,
int
dest)
{
List<List<
int
>> edgePath =
new
List<List<
int
>>();
List<
int
> tempEdge =
new
List<
int
>();
bool
[] vis =
new
bool
[n];
DfsAll(n, src, dest, graph, vis, edgePath, tempEdge);
return
GetDistance(edgePath, k);
}
static
void
Main()
{
int
n = 5, k = 1;
List<List<Tuple<
int
,
int
>>> graph =
new
List<List<Tuple<
int
,
int
>>>(n);
for
(
int
i = 0; i < n; i++)
graph.Add(
new
List<Tuple<
int
,
int
>>());
graph[0].Add(
new
Tuple<
int
,
int
>(1, 1));
graph[1].Add(
new
Tuple<
int
,
int
>(0, 1));
graph[0].Add(
new
Tuple<
int
,
int
>(4, 1));
graph[4].Add(
new
Tuple<
int
,
int
>(0, 1));
graph[1].Add(
new
Tuple<
int
,
int
>(2, 2));
graph[2].Add(
new
Tuple<
int
,
int
>(1, 2));
graph[2].Add(
new
Tuple<
int
,
int
>(3, 4));
graph[3].Add(
new
Tuple<
int
,
int
>(2, 4));
graph[4].Add(
new
Tuple<
int
,
int
>(3, 7));
graph[3].Add(
new
Tuple<
int
,
int
>(4, 7));
int
a = 0, b = 3;
Console.WriteLine(Solve(graph, n, k, a, b));
}
}