2018-03-13 L2

L2-001. 紧急救援
谢谢大佬代码
dijkstra

#include 
#include 
using namespace std;
int const MAX = 505;
int const INF = 0x3fffffff;
int mp[MAX][MAX], val[MAX], path[MAX], dis[MAX], re[MAX], totval[MAX], pathnum[MAX];
bool vis[MAX];
int n, m, s, d;
void Dijkstra(int v0)
{
    for(int i = 0; i < n; i++)
        dis[i] = INF;
    vis[v0] = true;
    dis[v0] = 0;
    totval[v0] = val[v0];
    pathnum[v0] = 1;
    for(int i = 0; i < n; i++)
    {
        if(mp[v0][i] != INF && i != v0)
        {
            dis[i] = mp[v0][i];
            path[i] = v0;
            totval[i] = val[v0] + val[i];
            pathnum[i] = 1;
        }
    }
    for(int i = 0; i < n - 1; i++) // 添加 n-1 个点
    {
        int mi = INF, mival = 0, u = v0;
        for(int j = 0; j < n; j++)
        {
            if(!vis[j] && dis[j] < mi)
            {
                mi = dis[j];
                u = j;
            }
        }
        vis[u] = true;  // 找到距离最近的点
        for(int j = 0; j < n; j++)  // 添加了这个点 更新 dis
        {
            if(!vis[j]) //未放入集合中点
            {
                if(dis[u] + mp[u][j] < dis[j]) // 距离更新
                {
                    pathnum[j] = pathnum[u];
                    dis[j] = dis[u] + mp[u][j];
                    totval[j] = totval[u] + val[j];
                    path[j] = u;
                }
                else if(dis[u] + mp[u][j] == dis[j])    // 如果相等
                {
                    pathnum[j] += pathnum[u];           // 更新路径条数
                    if(totval[j] < totval[u] + val[j])
                    {
                        totval[j] = totval[u] + val[j]; // 更新个数
                        path[j] = u;                    // 更新前驱节点
                    }
                }
            }
        }
    }
}

int main()
{
    scanf("%d %d %d %d", &n, &m, &s, &d);
    for(int i = 0; i < n; i++)
        scanf("%d", &val[i]);
    for(int i = 0; i < n; i++)
        for(int j = 0; j < n; j++)
            mp[i][j] = INF;
    int x, y, l;
    for(int i = 0; i < m; i++)
    {
        scanf("%d %d %d", &x, &y, &l);
        mp[x][y] = min(mp[x][y], l);
        mp[y][x] = mp[x][y];
    }
    Dijkstra(s);
    int num = 0, cur = d;
    while(cur != s)
    {
        re[num ++] = cur;
        cur = path[cur];
    }
    re[num ++] = s;
    printf("%d %d\n", pathnum[d], totval[d]);
    for(int i = num - 1; i > 0; i--)
        printf("%d ", re[i]);
    printf("%d\n", re[0]);
}

spfadr

你可能感兴趣的:(2018-03-13 L2)