SPFA+SLF+LLL优化模板

 1 #include<algorithm>
 2 #include <iostream>
 3 #include  <cstdlib>
 4 #include  <cstring>
 5 #include  <climits>
 6 #include   <cstdio>
 7 #include   <string>
 8 #include    <cmath>
 9 #include    <stack>
10 #include    <deque>
11 
12 using namespace std;
13 const int INF=1<<30;
14 const int gg=200000 + 11;
15 int head[gg];
16 int dis[gg];
17 int n,m;
18 int cnt;
19 bool vis[gg];
20 int sum,tot;
21 struct node{
22     int net;
23     int to;
24     int w;
25 }a[gg];
26 
27 inline void add(int i,int j,int w)
28 {
29     a[++cnt].to=j;
30     a[cnt].net=head[i];
31     a[cnt].w=w;
32     head[i]=cnt;
33 }
34 
35 inline void spfa(int s)
36 {
37     deque<int>q;
38     for(int i=1;i<=n;i++)
39         dis[i]=INF;
40     dis[s]=0;
41     vis[s]=true;    
42     q.push_back(s);
43     tot=1;
44     while(!q.empty())
45     {
46         int u=q.front();
47         q.pop_front();
48         vis[u]=false;
49         tot--;
50         sum-=dis[u];
51         for(int i=head[u];~i;i=a[i].net)
52         {
53             int v=a[i].to;
54             if(dis[v]>dis[u]+a[i].w)
55             {
56                 dis[v]=dis[u]+a[i].w;
57                 if(!vis[v])
58                 {
59                     vis[v]=true;
60                     if(q.empty()||dis[v]>dis[q.front()]||dis[v]*tot<=sum)
61                     q.push_back(v);
62                     tot++;
63                     sum+=dis[v];
64                 }
65             }
66         }
67     }
68 }
69 
70 int main()
71 {
72     memset(head,-1,sizeof(head));
73     cin>>n>>m;
74     for(int i=1;i<=m;i++)
75     {
76         int a,b,c;
77         cin>>a>>b>>c;
78         add(a,b,c);
79         add(b,a,c);
80     }
81     spfa(1);
82     if(dis[n]==INF)
83     {
84         cout<<-1<<endl;
85         return 0;
86     }
87     else
88     {
89         cout<<dis[n]<<endl;
90     }
91     return 0;
92 }

 

posted @ 2017-11-09 07:48  Hammer_cwz_77  阅读(767)  评论(0编辑  收藏  举报