zoukankan      html  css  js  c++  java
  • SPFA 邻接表

    SPFA 模板

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<queue>
    using namespace std;
    
    const long MAXN=9999;
    const long maxn=0x7fffffff;
    
    bool visit[MAXN];
    long dis[MAXN],n,m,u,v,len;
    long head[MAXN],num_edge;
    queue<long>que;
    
    struct Edge {
        long pre,to,len;
    } edge[MAXN];
    
    void add(int u,int v,int w) {
        edge[++num_edge].pre=head[u];
        edge[num_edge].to=v;
        edge[num_edge].len=len;
        head[u]=num_edge;
    }
    
    void in() {
        memset(visit,false,sizeof(visit));
        memset(head,-1,sizeof(head));
        fill(dis,dis+MAXN,maxn);
        while(!que.empty())
            que.pop();
        num_edge=0;
        for(long i=1; i<=m; i++) {
            cin>>u>>v>>len;
            add(u,v,len);
            add(v,u,len);
        }
    }
    
    void print(int e) {
        cout<<dis[e]<<endl;
    }
    
    void spfa() {
        in();
        long a,e;
        cin>>a>>e;
        dis[a]=0;
        visit[a]=true;
        que.push(a);
        while(!que.empty()) {
            long k=que.front();
            que.pop();
            visit[k]=false;
            for(long j=head[k]; j!=-1; j=edge[j].pre) {
                long w=edge[j].len;
                if(dis[edge[j].to]>dis[k]+w) {
                    dis[edge[j].to]=dis[k]+w;
                    if(!visit[edge[j].to]) {
                        visit[edge[j].to]=true;
                        que.push(edge[j].to);
                    }
                }
            }
        }
        print(e);
    }
    
    int main() {
        cin>>n>>m;
        spfa();
        return 0;
    }

    自己选的路,跪着也要走完!!!

  • 相关阅读:
    React Native 项目常用第三方组件汇总
    react-native-swiper的Github地址
    Navicat for MySQL 使用
    maven项目创7 配置分页插件
    rander()函数执行条件
    RN生命周期
    react-native连接夜神模拟器
    让PHP7达到最高性能的几个Tips
    php安装
    被swoole坑哭的PHP程序员
  • 原文地址:https://www.cnblogs.com/wsdestdq/p/6694683.html
Copyright © 2011-2022 走看看