using
System;
using
System.Collections.Generic;
using
System.Linq;
public
class
PriorityQueue<T>
{
private
List<T> heap;
private
Comparison<T> comparator;
public
PriorityQueue(Comparison<T> comparator)
{
heap =
new
List<T>();
this
.comparator = comparator;
}
public
void
Push(T value)
{
heap.Add(value);
heap.Sort(comparator);
}
public
T Pop()
{
T frontItem = heap.First();
heap.RemoveAt(0);
return
frontItem;
}
public
bool
IsEmpty()
{
return
heap.Count == 0;
}
}
public
class
PQPair
{
public
int
[] First {
get
;
set
; }
public
int
[] Second {
get
;
set
; }
public
PQPair(
int
[] first,
int
[] second)
{
First = first;
Second = second;
}
}
class
Program
{
const
int
N = 100005;
static
List<
int
[]>[] incr = Enumerable.Range(0, N).Select(_ =>
new
List<
int
[]>()).ToArray();
static
List<
int
[]>[] decr = Enumerable.Range(0, N).Select(_ =>
new
List<
int
[]>()).ToArray();
static
int
[] _incr =
new
int
[N];
static
int
[] _decr =
new
int
[N];
static
int
[] shortest =
new
int
[N];
static
int
n, src, dest;
static
int
MAXI = 1 << 30;
static
void
Add_edge(
int
x,
int
y,
int
w)
{
incr[x].Add(
new
int
[] { w, y });
incr[y].Add(
new
int
[] { w, x });
decr[x].Add(
new
int
[] { -w, y });
decr[y].Add(
new
int
[] { -w, x });
}
static
int
Modified_Dijkstra()
{
var
q =
new
PriorityQueue<PQPair>((a, b) => b.First[0] - a.First[0]);
for
(
int
i = 1; i <= n; i++)
{
incr[i].Sort((a, b) => (a[0] != b[0]) ? a[0] - b[0] : a[1] - b[1]);
decr[i].Sort((a, b) => (a[0] != b[0]) ? a[0] - b[0] : a[1] - b[1]);
}
for
(
int
i = 1; i <= n; i++)
shortest[i] = MAXI;
q.Push(
new
PQPair(
new
int
[] { 0, 0 },
new
int
[] { 0, src }));
while
(!q.IsEmpty())
{
var
FRONT = q.Pop();
int
cost = -FRONT.First[0];
int
stage = FRONT.First[1];
int
weight = FRONT.Second[0];
int
v = FRONT.Second[1];
shortest[v] = Math.Min(shortest[v], cost);
if
(shortest[dest] != MAXI)
break
;
if
(stage == 1)
{
for
(
int
i = _incr[v]; i < incr[v].Count; i++)
{
if
(weight > incr[v][i][0])
q.Push(
new
PQPair(
new
int
[] { -cost - incr[v][i][0], 0 },
new
int
[] { incr[v][i][0], incr[v][i][1] }
));
else
{
_incr[v] = i;
break
;
}
}
}
else
{
for
(
int
i = _decr[v]; i < decr[v].Count; i++)
{
if
(weight < -decr[v][i][0])
q.Push(
new
PQPair(
new
int
[] { -cost + decr[v][i][0], 1 },
new
int
[] { -decr[v][i][0], decr[v][i][1] }
));
else
{
_decr[v] = i;
break
;
}
}
}
}
if
(shortest[dest] == MAXI)
return
-1;
return
shortest[dest];
}
static
void
Main(
string
[] args)
{
n = 5; src = 4; dest = 3;
Add_edge(4, 2, 8);
Add_edge(1, 4, 6);
Add_edge(2, 3, 10);
Add_edge(3, 1, 10);
Add_edge(1, 2, 3);
Add_edge(3, 5, 3);
Console.WriteLine(Modified_Dijkstra());
}
}