spfa

来源:互联网 发布:淘宝买东西质量问题 编辑:程序博客网 时间:2024/05/02 04:37
///复杂度为k*maxe 一般k<=2
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int maxv=1001;
const int maxe=4001;
const int oo=1000000000;
struct node{
int w,to,next;
}e[maxe];
int head[maxv],dis[maxv];
int edge,n,m;
bool vis[maxv];
queue<int>q;
void add(int u,int v,int c)
{
    e[edge].to=v,e[edge].w=c,e[edge].next=head[u],head[u]=edge++;
}
bool spfa(int s)
{
    int v,i;
    while(!q.empty()) q.pop();
    for(i=1;i<=n;i++)
    dis[i]=(i==s?0:oo);
    memset(vis,0,sizeof(vis));
    vis[s]=1;
    q.push(s);
    while(!q.empty())
    {
        int tmp=q.front();
        q.pop();
        for(i=head[tmp];i!=-1;i=e[i].next)
        {
            if(dis[tmp]+e[i].w<dis[v=e[i].to])
            {
                dis[v]=dis[tmp]+e[i].w;
                if(!vis[v])
                {
                    vis[v]=true;
                    q.push(v);
                }
            }
        }
        vis[tmp]=false;
    }
    return true;
}
int main()
{
    int u,v,d;
   while(cin>>m>>n)
   {
       edge=0;
       memset(head,-1,sizeof(head));
       for(int i=0;i<m;i++)
       {
           cin>>u>>v>>d;
           add(u,v,d);
           add(v,u,d);
       }
       spfa(1);
       cout<<dis[n]<<endl;
   }
    return 0;
}
原创粉丝点击