#include<iostream>
#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;
struct Node
{
int e,w;
};
const int inf = (1<<25);
int main()
{
vector <Node> G[5005];
int n, m, num, cc;
cin >> n >> m;
for (int i = 1; i <= m; i++)
{
Node q;
int u, v, cost;
cin >> u>> v >> cost;
q.e = v;
q.w = cost;
G[u].push_back(q);
q.e = u;
q.w = cost;
G[v].push_back(q); //此题是双向的
}
int s, f;
s = 1;
f = n;
int flag[5005][2], dis[5005][2], cnt[5005][2];
memset(flag, 0, sizeof(flag));
for (int i = 1; i <= n; i++)
dis[i][0] = dis[i][1] = inf;
dis[s][0] = 0;
cnt[s][0] = 1;
while (1)
{
int temp = inf, u = -1, k;
for (int j = 1; j <= n; j++)
{
if(flag[j][0]==0&&temp>dis[j][0]) temp=dis[j][0],u=j,k=0;
else if(flag[j][1]==0&&temp>dis[j][1]) temp=dis[j][1],u=j,k=1;
}
if (temp == inf) break;
flag[u][k] = 1;
for (int l = 0; l < G[u].size(); l++)
{
int d = dis[u][k] + G[u][l].w, j = G[u][l].e;
if (d < dis[j][0])
{
dis[j][1] = dis[j][0];cnt[j][1] = cnt[j][0];
dis[j][0] = d;cnt[j][0] = cnt[u][k];
}
else if (d == dis[j][0])
{
cnt[j][0] += cnt[u][k];
}
else if (d < dis[j][1])
{
dis[j][1] = d;cnt[j][1] = cnt[u][k];
}
else if (d == dis[j][1])
{
cnt[j][1] += cnt[u][k];
}
}
num = dis[f][0]; // 最短路长度
cc = dis[f][1]; //次短路长度
//cnt[][0]记录最短路条数 cnt[][1]记录次短路条数
}
printf("%d\n", cc);
return 0;
}
POJ 3255 Roadblocks(Dijstra 求次短路长度)
最新推荐文章于 2021-09-15 23:34:29 发布