10986 - Sending email//Bellman-Ford

题目分析:裸的最短路,但是结点有点多,用邻接矩阵会RE,用邻接链表存储图。然后就BallmanFord了。

吐槽:首先没看数据一直RE,各种RE,然后输出的时候#和数字写反了,一直WA,囧!

代码:

#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
const int INF = 2000000010;
const int maxn = 2*50005;
int u[maxn],v[maxn],w[maxn];
int first[maxn],next[maxn];
int n,m,s,t;
queue<int> q;
bool inq[maxn];
int d[maxn];
void Bellman_Ford()
{
    for(int i = 0; i < n; i++) d[i] = INF,inq[i] = false;
    d[s] = 0;
    q.push(s); inq[s] = true;
    while(!q.empty())
    {
        int x = q.front(); q.pop();
        inq[x] = false;
        for(int e = first[x]; e != -1; e = next[e])
        {
            if(d[v[e]] > d[x] + w[e])
            {
                d[v[e]] = d[x] + w[e];
                if(!inq[v[e]])
                {
                    inq[v[e]] = true;
                    q.push(v[e]);
                }
            }
        }
    }
}
int main()
{
    int N;
    scanf("%d",&N);
    for(int k = 1; k <= N; k++)
    {
        scanf("%d%d%d%d",&n,&m,&s,&t);
        for(int i = 0; i < n; i++) first[i] = -1;

        for(int e = 0,i = 0; i < m; e += 2,i++)
        {
            scanf("%d%d%d",&u[e],&v[e],&w[e]);
            next[e] = first[u[e]];
            first[u[e]] = e;

            u[e+1] = v[e];
            v[e+1] = u[e];
            w[e+1] = w[e];
            next[e+1] = first[v[e]];
            first[v[e]] = e + 1;
        }

        Bellman_Ford();
        printf("Case #%d: ",k);
        if(d[t] != INF) printf("%d\n",d[t]);
        else printf("unreachable\n");
    }
    return 0;
}

    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/mr_zys/article/details/8940243
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞