给一个图,求出1到n的次短路。
迪杰斯特拉的题,只是需要变很多。
#pragma warning(disable:4996)
#include <cstring>
#include<cstdio>
#include <algorithm>
#include<iostream>
#include<cmath>
#include<queue>
#include<set>
#include<vector>
#include<stack>
using namespace std;
typedef long long ll;
const int inf = INT_MAX;
const int maxn = 50005;
int n,cnt;
int dis[maxn][2],head[maxn];
bool vis[maxn][2];
struct node
{
int v, next, w;
};
node edge[maxn << 2];
void add(int u, int v, int w)//加边
{
edge[++cnt].v = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt;
}
void dijkstra()
{
int i, j;
for (i = 1;i <= n;i++)//初始化
{
dis[i][0] = dis[i][1] = inf;
vis[i][0] = vis[i][1] = 0;
}
dis[1][0] = 0;
for (i = 1;i < 2 * n;i++)
{
int MIN = inf, k, flag;
for (j = 1;j <= n;j++)
{
if (!vis[j][0] && dis[j][0] < MIN)
{
MIN = dis[j][0];
k = j;
flag = 0;
}
else if (!vis[j][1] && dis[j][1] < MIN)
{
MIN = dis[j][1];
k = j;
flag = 1;
}
}//找到最短路或者次短路
if (MIN == inf)break;
vis[k][flag] = 1;
for (j = head[k];j != -1;j = edge[j].next)
{
int v = edge[j].v;
int w = edge[j].w;
if (w + MIN <= dis[v][0])//比最短路短,更新最短和次短
{
dis[v][1] = dis[v][0];
dis[v][0] = w + MIN;
}
else if (w + MIN < dis[v][1])//否则只比次短路短,更新次短路
{
dis[v][1] = w + MIN;
}
}
}
printf("%d\n", dis[n][1]);
}
int main()
{
int i, j, t1, t2, t3,m;
while (scanf("%d%d", &n, &m) == 2)
{
for (i = 1;i <= n;i++)
head[i] = -1;
cnt = 0;
while (m--)
{
scanf("%d%d%d", &t1, &t2, &t3);
add(t1, t2, t3);
add(t2, t1, t3);
}
dijkstra();
}
return 0;
}