您的位置:首页 > 其它

SPFA算法模板

2015-10-09 18:59 399 查看
[code]#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int size = 200010;
int head[size],next[size],dist[size];
struct dc
{
    int t,d;
}l[size];
bool use[size];
int pri[size];
int t,c,s,e;
int tot = 1;
void build(int f,int t,int d)
{
    l[tot].d = d;
    l[tot].t = t;
    next[tot] = head[f];
    head[f] = tot ++;
}
queue < int > q;
void spfa(int s)
{
    dist[s] = 0;
    use[s] = 1;
    q.push(s);
    while(!q.empty())
    {
        int f = q.front();
        q.pop();
        use[f] = 0;
        for(int i = head[f] ; i ; i = next[i])
        {
            int t = l[i].t;
            if(dist[t] > dist[f] + l[i].d)
            {
                dist[t] = dist[f] + l[i].d;
                pri[t] = f;
                if(!use[t])
                {
                    use[t] = 1;
                    q.push(t);
                }
            }
        }
    }
}
int main()
{
    scanf("%d%d%d%d",&t,&c,&s,&e);
    for(int i = 1 ; i <= t ; i ++)
        dist[i] = 214748364;
    for(int i = 1 ; i <= c ; i ++)
    {
        int f,t,d;
        scanf("%d%d%d",&f,&t,&d);
        build(f,t,d);
        build(t,f,d);
    }
    spfa(s);
    printf("%d",dist[e]);
    return 0;
}


例题codevs1557 , 两点间的最短路径
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: