zoukankan      html  css  js  c++  java
  • [模板][HDU]P2544[单源最短路][SPFA]

    题目就不放了,主要是写一下SPFA,很少写,今天特别学了一个用STL的队列来做的。

    代码:

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<queue>
     5 using namespace std;
     6 inline int read();
     7 namespace lys{
     8     const int N = 1e2 + 7 ;
     9     const int M = 1e4 + 7 ;
    10     struct edge{
    11         int to;
    12         int next;
    13         int w;
    14     }e[M*3];
    15     int n,m,cnt;
    16     int pre[N],dis[N];
    17     bool exist[N];
    18     void add(int x,int y,int w){
    19         e[++cnt].to=y;e[cnt].next=pre[x];pre[x]=cnt;e[cnt].w=w;
    20         e[++cnt].to=x;e[cnt].next=pre[y];pre[y]=cnt;e[cnt].w=w;
    21     }
    22     int spfa(){
    23         memset(dis,127,sizeof dis);
    24         dis[1]=0;
    25         queue <int> q;
    26         q.push(1),exist[1]=true ;
    27         int x,i,v;
    28         while(!q.empty()){
    29             x=q.front(),q.pop();
    30             exist[x]=false ;
    31             for(i=pre[x];i;i=e[i].next){
    32                 v=e[i].to;
    33                 if(dis[x]+e[i].w<dis[v]){
    34                     dis[v]=dis[x]+e[i].w;
    35                     if(!exist[v]) q.push(v);
    36                 }
    37             }
    38         }
    39         return dis[n];
    40     }
    41     int main(){
    42         int x,y,w;
    43         while(true){
    44             n=read(); m=read();
    45             if(n==0) return 0;
    46             memset(pre,0,sizeof pre);
    47             cnt=0;
    48             while(m--){
    49                 x=read(); y=read(); w=read();
    50                 add(x,y,w);
    51             }
    52             printf("%d
    ",spfa());
    53         }
    54         return 0;
    55     }
    56 }
    57 int main(){
    58     lys::main();
    59     return 0;
    60 }
    61 inline int read(){
    62     int kk=0,ff=1;
    63     char c=getchar();
    64     while(c<'0'||c>'9'){
    65         if(c=='-') ff=-1;
    66         c=getchar();
    67     }
    68     while(c>='0'&&c<='9') kk=kk*10+c-'0',c=getchar();
    69     return kk*ff;
    70 }
  • 相关阅读:
    【QT】读取目录文件,双击显示文件内容
    【QT】简易计算器实现
    【QT】使用代码方式实现简单的界面布局
    【QT】event事件使用鼠标位置
    【ffmpeg】FFMPEG常用命令
    【QT】简单文本编辑器,open,save功能
    Nginx--try_files尝试读取文件
    深浅拷贝
    CNN卷积神经网络学习笔记
    深度学习基础学习-第二章-感知器
  • 原文地址:https://www.cnblogs.com/_inx/p/7805669.html
Copyright © 2011-2022 走看看