hihoCoder#1093 最短路径·三:SPFA算法

原题地址

 

宽搜+剪枝,不是说好了适用于稀疏矩阵的嘛,怎么题目的测试数据边数达到10^6。。。不科学

 

代码:

 1 #include <iostream>

 2 #include <cstring>

 3 #include <map>

 4 

 5 using namespace std;

 6 

 7 #define MAX_POINT 100008

 8 #define MAX_EDGE 1000008

 9 

10 int N, M, S, T;

11 int p[MAX_POINT];

12 int q[MAX_POINT];

13 int d[MAX_POINT];

14 map<int, map<int, int> > g;

15 int head, tail;

16 

17 void spfa() {

18   for (int i = 0; i < N; i++)

19     p[i] = -1;

20   memset(d, 1, sizeof(d));

21   head = tail = 0;

22   d[S] = 0;

23   p[S] = tail;

24   q[tail++] = S;

25 

26   while (head < tail) {

27     int s = q[head++];

28     for (auto t : g[s]) {

29       int len = d[s] + t.second;

30       if (len < d[t.first]) {

31         d[t.first] = len;

32         if (p[t.first] < 0) {

33           p[t.first] = tail;

34           q[tail++] = t.first;

35         }

36       }

37     }

38     p[s] = -1;

39   }

40 }

41 

42 int main() {

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

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

45     int a, b, len;

46     scanf("%d%d%d", &a, &b, &len);

47     if (!g[a][b])

48       g[a][b] = g[b][a] = len;

49     else

50       g[a][b] = g[b][a] = min(g[a][b], len);

51   }

52 

53   spfa();

54 

55   printf("%d\n", d[T]);

56 

57   return 0;

58 }

 

你可能感兴趣的:(code)