SPFA模板,链式前向星

模板

 1 #include <cstdio>
 2 #include <queue>
 3 #include <cstring>
 4 #include <algorithm>
 5 
 6 using namespace std;
 7 
 8 int n, p, c, ans, cnt;
 9 long long m;
10 struct node
11 {
12     int to, next;
13 }edge[5000001];
14 int dis[5000001], head[500001], x, y;
15 bool vis[5000001];
16 
17 void spfa()
18 {
19     int i, j;
20     queue <int> q;
21     memset(dis, 0x7f, sizeof(dis));
22     dis[c] = 1;
23     vis[c] = 1;
24     q.push(c);
25     while(!q.empty())
26     {
27         i = q.front();
28         q.pop();
29         vis[i] = 0;
30         for(j = head[i]; j >= 0; j = edge[j].next)
31          if(dis[edge[j].to] > dis[i] + 1)
32          {
33              dis[edge[j].to] = dis[i] + 1;
34              if(!vis[edge[j].to])
35              {
36                  q.push(edge[j].to);
37                  vis[edge[j].to] = 1;
38              }
39          }
40     }
41 }
42 
43 int main()
44 {
45     int i, j;
46     scanf("%d %d %d", &n, &p, &c);
47     scanf("%d", &m);
48     memset(head, -1, sizeof(head));
49     for(i = 1; i <= p; i++)
50     {
51         scanf("%d %d", &x, &y);
52         edge[cnt].to = y;
53         edge[cnt].next = head[x];
54         head[x] = cnt++;
55         edge[cnt].to = x;
56         edge[cnt].next = head[y];
57         head[y] = cnt++;
58     }
59     spfa();
60     for(i = 1; i <= n; i++) ans = max(ans, dis[i]);
61     printf("%lld", ans + m);
62     return 0;
63 }
链式前向星

完事

posted @ 2017-05-17 17:31  秦时、长浩  阅读(179)  评论(0编辑  收藏  举报