Dijkstra算法 —PAT甲级 1003 Emergency题解

1003 Emergency

原题链接

开两个数组分别记录到当前顶点最短路径条数以及最大权值和,Dijkstra更新最短路径的时候分别更新这两个数组(讨论两种情况)
注意点:

  1. 存在起始点和结束点相同的情况,这种情况路径数需要输出1(测试点1)
  2. 路是双向的,所以题目中给的图是无向图(没有注意到这一点的会卡测试点2和5)

AC代码

#include 
#include 
#include 
#define maxv 501
#define INF 1e9

using namespace std;

void Dijkstra(void);

struct Edge{
    int to;
    int weight;
};

int N, M, st, en;
int emer[maxv], w[maxv] = {0}, num[maxv] = {0}, dist[maxv];
bool vis[maxv] = {false};
vector<Edge> G[maxv];

int main()
{
    cin >> N >> M >> st >> en;
    fill(dist, dist+maxv, INF);
    for (int i=0; i<N; i++)
        cin >> emer[i];
    for (int i=0; i<M; i++)
    {
        int v;
        Edge e1, e2;
        cin >> v >> e1.to >> e1.weight;
        e2.to = v;
        e2.weight = e1.weight;
        G[v].push_back(e1);
        G[e1.to].push_back(e2);
        if (v == st)
        {
            dist[e1.to] = e1.weight;
            num[e1.to] = 1;
            w[e1.to] = emer[st]+emer[e1.to];
        }
    }
    w[st] = emer[st];
    num[st] = 1;
    vis[st] = true;
    Dijkstra();
    cout << num[en] << ' ' << w[en];
    return 0;
}

void Dijkstra(void)
{
    for(int i=0; i<N; i++)
    {
        int MIN=INF, u=-1;
        for (int j=0; j<N; j++)
        {
            if (vis[j]==false && dist[j]<MIN)
            {
                MIN = dist[j];
                u = j;
            }
        }
        if (MIN == INF)
            return;
        vis[u] = true;
        for (int j=0; j<G[u].size(); j++)
        {
            int v, wei;
            v = G[u][j].to, wei = G[u][j].weight;
            if (dist[u]+wei < dist[v])          //第一种情况,更新
            {
                dist[v] = dist[u]+wei;
                num[v] = num[u];
                w[v] = w[u]+emer[v];
            }
            else if (dist[u]+wei == dist[v])    //第二种情况,更新
            {
                num[v] += num[u];
                if(w[v] < w[u]+emer[v])
                    w[v] = w[u]+emer[v];
            }
        }
    }
}

你可能感兴趣的:(PAT)