PTA L2-001 紧急救援(dijkstra+路径打印)

  • Post author:
  • Post category:其他


在这里插入图片描述

好久没写dj生疏了,嫖别人的代码

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

#define iosy ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
const int N = 5e2 + 5;
int g[N][N];
int dist[N];
bool st[N]; //点的状态
int c[N];   //救援队数目
int a[N];
int cnt[N], sum[N], pre[N]; //最短路径条数,当前路径救援队数目,前置节点
int n, m, s, d;

vector<int> path; //路径

void dijkstra()
{
    memset(dist, 0x3f, sizeof(dist));

    dist[s] = 0, cnt[s] = 1, sum[s] = c[s], pre[s] = s;

    for (int i = 0; i < n; i++)
    {
        int t = -1;
        for (int j = 0; j < n; j++) // 找到当前与源点最近的点, 通过这个点来更新其它的点
        {
            if (st[j] == false && (t == -1 || dist[t] > dist[j]))
                t = j;
        }
        st[t] = true;

        for (int j = 0; j < n; j++)
        {
            if (st[j] == false && dist[j] == dist[t] + g[t][j]) // 若距离相等, 更新救援队数量更多的
            {
                cnt[j] += cnt[t];
                if (sum[j] < sum[t] + c[j])
                {
                    sum[j] = sum[t] + c[j];
                    pre[j] = t;
                }
            }
            else if (st[j] == false && dist[j] > dist[t] + g[t][j]) //有更短路径就更新
            {
                dist[j] = dist[t] + g[t][j];
                cnt[j] = cnt[t];
                sum[j] = sum[t] + c[j];
                pre[j] = t;
            }
        }
    }
}
void solve()
{
    cin >> n >> m >> s >> d;
    for (int i = 0; i < n; i++)
        cin >> c[i], g[i][i] = 0;
    memset(g, 0x3f, sizeof(g));

    for (int i = 1; i <= m; i++)
    {
        int x, y, z;
        cin >> x >> y >> z;
        g[x][y] = g[y][x] = z;
    }

    dijkstra();

    // for (int i = 0; i < n; i++)
    //     for (int j = 0; j < n; j++)
    //     {
    //         cout << i << " " << j << " " << g[i][j] << endl;
    //     }
    cout << cnt[d] << " " << sum[d] << endl;
    int tail = d;
    while (tail != s)
    {
        path.push_back(tail);
        tail = pre[tail];
    }
    path.push_back(s);
    for (int i = path.size() - 1; i >= 0; i--)
    {
        if (!i)
            cout << path[i];
        else
            cout << path[i] << " ";
    }
}
int main()
{
    iosy;
    solve();

    return 0;
}



版权声明:本文为qq_53485165原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。