zoukankan      html  css  js  c++  java
  • wenbao与最短路(spfa)

    spfa就是利用邻接表和队列进行优化的最短路!!!

    牛!!!

    利用spfa判断图中的负环:如果一个点入队次数超过n则存在负环

     1 #include <iostream>
     2 #include <string.h>
     3 #include <queue>
     4 #include <vector>
     5 using namespace std;
     6 const int maxn =  1010;
     7 int n, m, s, t, from, to, val, T[maxn];
     8 bool mark[maxn];
     9 vector<int> a[maxn];
    10 vector<int> b[maxn];
    11 void spfa(){
    12     memset(T, 0x3f, sizeof(T));
    13     T[s] = 0;
    14     queue<int> q;
    15     q.push(s);
    16     while(!q.empty()){
    17         int k = q.front();
    18         q.pop();
    19         mark[k] = false;
    20         for(int i = 0; i < a[k].size(); i++)if(T[k] + b[k][i] < T[a[k][i]])    {
    21             T[a[k][i]] = T[k] + b[k][i];
    22             if(!mark[a[k][i]]){
    23                 q.push(a[k][i]);
    24                 mark[a[k][i]] = true;
    25             }
    26         }
    27     }
    28 }
    29 int main(){
    30     scanf("%d %d %d %d", &n, &m, &s, &t);
    31     for(int i = 0; i < m; i++) {
    32         scanf("%d %d %d", &from, &to, &val);
    33         a[from].push_back(to);
    34         b[from].push_back(val);
    35         a[to].push_back(from);
    36         b[to].push_back(val);
    37     }
    38     spfa();
    39     printf("%d
    ", T[t]);
    40     return 0;
    41 }

    只有不断学习才能进步!

  • 相关阅读:
    线程
    进程2
    进程
    socketserver
    黏包
    初始网络编程
    模块
    super
    mro c3算法
    日志固定格式
  • 原文地址:https://www.cnblogs.com/wenbao/p/5899691.html
Copyright © 2011-2022 走看看