using
System;
using
System.Collections.Generic;
using
System.Linq;
public
class
ShortestPath {
public
static
void
FindKShortest(
int
[, ] edges,
int
n,
int
m,
int
k)
{
List<List<KeyValuePair<
int
,
int
> > > g
=
new
List<List<KeyValuePair<
int
,
int
> > >();
for
(
int
i = 0; i <= n; i++) {
g.Add(
new
List<KeyValuePair<
int
,
int
> >());
}
for
(
int
i = 0; i < m; i++) {
g[edges[i, 0]].Add(
new
KeyValuePair<
int
,
int
>(
edges[i, 1], edges[i, 2]));
}
int
[][] dis =
new
int
[n + 1][];
for
(
int
i = 0; i <= n; i++) {
dis[i] = Enumerable.Repeat(
int
.MaxValue, k)
.ToArray();
}
var
pq
=
new
PriorityQueue<KeyValuePair<
int
,
int
> >();
pq.Enqueue(
new
KeyValuePair<
int
,
int
>(0, 1));
dis[1][0] = 0;
while
(pq.Count > 0) {
int
u = pq.Peek().Value;
int
d = pq.Peek().Key;
pq.Dequeue();
if
(dis[u][k - 1] < d)
continue
;
List<KeyValuePair<
int
,
int
> > v = g[u];
for
(
int
i = 0; i < v.Count; i++) {
int
dest = v[i].Key;
int
cost = v[i].Value;
if
(d + cost < dis[dest][k - 1]) {
dis[dest][k - 1] = d + cost;
Array.Sort(dis[dest]);
pq.Enqueue(
new
KeyValuePair<
int
,
int
>(
d + cost, dest));
}
}
}
for
(
int
i = 0; i < k; i++) {
Console.Write(dis[n][i] +
" "
);
}
}
static
void
Main(
string
[] args)
{
int
N = 4, M = 6, K = 3;
int
[, ] edges
= { { 1, 2, 1 }, { 1, 3, 3 }, { 2, 3, 2 },
{ 2, 4, 6 }, { 3, 2, 8 }, { 3, 4, 1 } };
FindKShortest(edges, N, M, K);
Console.ReadKey();
}
}
public
class
PriorityQueue<T>
where
T : IComparable<T> {
private
List<T> data;
public
PriorityQueue() {
this
.data =
new
List<T>(); }
public
void
Enqueue(T item)
{
data.Add(item);
int
ci
= data.Count - 1;
while
(ci > 0) {
int
pi = (ci - 1) / 2;
if
(data[ci].CompareTo(data[pi]) >= 0)
break
;
if
(d + cost < dis[dest][k - 1]) {
dis[dest][k - 1] = d + cost;
dis[dest].Sort();
pq.Enqueue(
new
KeyValuePair<
int
,
int
>(
d + cost, dest));
}
}
}
}
for
(
int
i = 0; i < k; i++) {
Console.Write(dis[n][i] +
" "
);
}
}
static
void
Main(
string
[] args)
{
int
N = 4, M = 6, K = 3;
int
[, ] edges
= { { 1, 2, 1 }, { 1, 3, 3 }, { 2, 3, 2 },
{ 2, 4, 6 }, { 3, 2, 8 }, { 3, 4, 1 } };
findKShortest(edges, N, M, K);
}
}
}