-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDijkstra.cs
executable file
·128 lines (108 loc) · 3.5 KB
/
Dijkstra.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dijkstra
{
class Program
{
static long[] d;
static int[] pi;
static void inicializar(List<Tuple<long, int>>[] grafo, int origen)
{
d = new long[grafo.Length];
pi = new int[grafo.Length];
//inicializar los arreglos
for (int i = 0; i < grafo.Length; i++)
{
d[i] = int.MaxValue;
pi[i] = int.MaxValue;
}
d[origen] = 0;
pi[origen] = -1;
}
static bool Relax(int u, int v, long w)
{
if (d[v] > d[u] + w)
{
d[v] = d[u] + w;
pi[v] = u;
return true;
}
else
return false;
}
// item1 es el costo
static void Dijkstra(List<Tuple<long, int>>[] grafo, int origen)
{
inicializar(grafo, origen);
SortedSet<Tuple<long, int>> avl = new SortedSet<Tuple<long, int>>();
avl.Add(new Tuple<long, int>(0, origen));
while (avl.Count != 0)
{
Tuple<long, int> elemento = avl.Min;
avl.Remove(avl.Min);
for (int i = 0; i < grafo[elemento.Item2].Count; i++)
{
Tuple<long, int> temp = grafo[elemento.Item2][i];
if (Relax(elemento.Item2, temp.Item2, temp.Item1))
{
Tuple<long, int> aux = new Tuple<long, int>(d[temp.Item2], temp.Item2);
if (avl.Contains(aux))
avl.Remove(aux);
avl.Add(new Tuple<long, int>(d[temp.Item2], temp.Item2));
}
}
}
}
static void Imprime<T>(T[] array)
{
for (int i = 1; i < array.Length; i++)
{
Console.Write("{0} ", array[i]);
}
Console.WriteLine();
}
static void Main(string[] args)
{
string[] linea = Console.ReadLine().Split();
int vertices = int.Parse(linea[0]);
int aristas = int.Parse(linea[1]);
List<Tuple<long, int>>[] grafo = new List<Tuple<long, int>>[vertices + 1];
for (int i = 0; i < grafo.Length; i++)
{
grafo[i] = new List<Tuple<long, int>>();
}
for (int i = 0; i < aristas; i++)
{
linea = Console.ReadLine().Split();
int u = int.Parse(linea[0]);
int v = int.Parse(linea[1]);
long costo = long.Parse(linea[2]);
grafo[u].Add(new Tuple<long, int>(costo, v));
}
int origen = int.Parse(Console.ReadLine());
//caso de la conferencia
//input
//5 10
//1 2 10
//2 4 1
//1 3 5
//3 5 2
//5 1 7
//3 4 9
//2 3 2
//3 2 3
//4 5 4
//5 4 6
//1
//output
//d = { 0, 8, 5, 9, 7 }
//pi = { -1, 3, 1, 2, 3 }
Dijkstra(grafo, origen);
Imprime(d);
Imprime(pi);
}
}
}