hihoCoder#1081 最短路径·一

原题地址

 

Dijkstra算法,甚至都不用优化(堆或优先队列)即可过

 

代码:

 1 #include <iostream>

 2 #include <vector>

 3 #include <set>

 4 #include <cstring>

 5 

 6 using namespace std;

 7 

 8 #define MAX_POINT 1024

 9 #define MAX_EDGE 16384

10 

11 int N, M, S, T;

12 int graph[MAX_POINT][MAX_POINT];

13 int v[MAX_POINT];

14 

15 void bfs() {

16   v[S] = 1;

17   while (true) {

18     int k = 0;

19     for (int i = 1; i <= N; i++) {

20       if (!v[i] && graph[S][i] < graph[S][k])

21         k = i;

22     }

23     if (k == T)

24       break;

25     v[k] = 1;

26     for (int i = 1; i <= N; i++)

27       if (!v[i] && graph[S][i] > graph[S][k] + graph[k][i])

28         graph[S][i] = graph[S][k] + graph[k][i];

29   }

30 }

31 

32 int main() {

33   memset(v, 0, sizeof(v));

34   memset(graph, 64, sizeof(graph));

35 

36   scanf("%d%d%d%d", &N, &M, &S, &T);

37   for (int i = 0; i < M; i++) {

38     int u, v, len;

39     scanf("%d%d%d", &u, &v, &len);

40     graph[u][v] = graph[v][u] = min(graph[u][v], len);

41   }

42 

43   bfs();

44 

45   printf("%d\n", graph[S][T]);

46 }

 

你可能感兴趣的:(code)