zoukankan      html  css  js  c++  java
  • [hdu2544]最短路spfa

    解题关键:最短路模板一直没整理过,这里整理了一下spfa+链式前向星建图的最短路模板,以后网络赛省的打了。

    spfa算法的关键就是松弛操作,只有进行松弛操作,其后的点距离才可能被更新。

     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 const int inf=0x3f3f3f3f;
     4 const int maxm=11111;
     5 const int maxn=111;
     6 int head[maxn],tot,n,m;
     7 struct edge{
     8     int to;
     9     int w;
    10     int nxt;
    11 }e[maxm];
    12 void add_edge(int u,int v,int w){
    13     e[tot].w=w;
    14     e[tot].to=v;
    15     e[tot].nxt=head[u];
    16     head[u]=tot++;
    17 }
    18 
    19 bool vis[maxn];
    20 queue<int>que;//队列是点的队列 
    21 int d[maxn];
    22 void spfa(int s){
    23     fill(d+1,d+n+1,inf); 
    24     memset(vis,0,sizeof vis);
    25     while (!que.empty()) que.pop();
    26     que.push(s);
    27     vis[s]=true;
    28     d[s]=0;
    29     while (!que.empty()){
    30         int u=que.front();
    31         que.pop();
    32         vis[u]=false;
    33         for (int i=head[u];i!=-1;i=e[i].nxt){
    34             int v=e[i].to;
    35             int w=e[i].w;
    36             if (d[v]>d[u]+w){
    37                 d[v]=d[u]+w;
    38                 if (!vis[v]){
    39                     vis[v]=true;
    40                     que.push(v);//hash一下,可判断是否存在负环 
    41                 }
    42             }
    43         }
    44     }
    45 }
    46 int main(){
    47     ios::sync_with_stdio(0);
    48     int a,b,c;
    49     while(cin>>n>>m&&(n||m)){
    50         tot=0;
    51         memset(head,-1,sizeof head); 
    52         for(int i=0;i<m;i++){
    53             cin>>a>>b>>c;
    54             add_edge(a,b,c);
    55             add_edge(b,a,c);
    56         }
    57         spfa(1);
    58         cout<<d[n]<<"
    ";
    59     }
    60     return 0;
    61 }
  • 相关阅读:
    HDU
    稀疏表(ST / Sparse Table)
    HDU
    HDU
    树状数组
    用 BitArray 来编写埃拉托斯特尼筛法
    BitArray 内置是逆序存储, 因此要自行实现正序输出
    位运算,位移,窗体
    按位运算,窗体程序,And,Or,Xor
    基数排序
  • 原文地址:https://www.cnblogs.com/elpsycongroo/p/7456173.html
Copyright © 2011-2022 走看看