代码:
int dij()
{
int i, j, vis[N];
for(i = 1; i <= n; i++)
vis[i] = mp[1][i];
vis[1] = 0;
for(i = 1; i <= n; i++)
{
int m = 1, f = inf;
for(j = 1; j <= n; j++)
{
if(f > vis[j] && !book[j])
{
m = j;
f = vis[j];
}
}
book[m] = 1;
for(j = 1; j <= n; j++)
{
if(!book[j] && vis[j] > vis[m] + mp[m][j])
vis[j] = vis[m] + mp[m][j];
}
}
return vis[n];
}
//n*log(n)
struct edge {int to, cost; };
typedef pair<int, int> P; // first 是最短距离,second是顶点编号
int V;
vector<edge> G[Max_V];
int d[Max_V];
void dijkstra(int s)
{
//通过指定greater<P>参数,堆按照first从小到大的循序取出值
priority_queue<P, vector<P>, greater<P> > que;
fill(d, d + V, INF);
d[s] = 0;
que.push(P(0, s));
while(!que.empty())
{
P p = que.top(); que.pop();
int v = p.second;
if(d[v] < p.first) continue;
for(int i = 0; i < G[v].size(); i++)
{
edge e = G[v][i];
if(d[e.to] > d[v] + e.cost)
{
d[e.to] = d[v] + e.cost;
que.push(P(d[e.to], e.to));
}
}
}
}
// Bellman_Fond复杂度O(VE)
struct edge {int from, to, cost; };
edge es[Max_E];
int d[Max_V];
int V, E;
void shortest_path(int s)
{
for(int i = 0; i < V; i++) d[i] = INF;
d[s] = 0;
while(true)
{
bool update = false;
for(int i = 0; i < E; i++)
{
edge e = es[i];
if(d[e.from != INF && d[e.to] > d[e.from] + e.cost)
{
d[e.to] = d[e.from] + e.cost;
update = true;
}
}
if(!update) break;
}
}
//开始时判断重边
bool find_negative_loop()
{
memset(d, 0, sizeof(d));
for(int i = 0; i < V; i++)
{
for(int j = 0; j < E; j++)
{
edge e = es[j];
if(d[e.to] > d[e.from] + e.cost)
{
d[e.to] = d[e.from] + e.cost;
if(i == V - 1) return false;
}
}
}
return true;
}
次短路:
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int MAXN = 100009;
const int INF = 0x3f3f3f3f;
typedef long long LL;
struct edge
{
int to, cost;
edge(int tv = 0, int tc = 0):
to(tv), cost(tc) {}
};
typedef pair<LL,int> P;
int N, R;
vector<edge> graph[MAXN];
LL dist[MAXN];
LL dist2[MAXN];
void solve()
{
memset(dist, 0x3f, sizeof(dist));
memset(dist2, 0x3f, sizeof(dist2));
priority_queue<P, vector<P>, greater<P> > Q;
dist[1] = 0ll;
Q.push(P(0, 1));
while(!Q.empty())
{
P p = Q.top();
Q.pop();
int v = p.second;
LL d = p.first;
if(dist2[v] < d) continue;
for(unsigned i = 0; i < graph[v].size(); i++)
{
edge &e = graph[v][i];
LL d2 = d + e.cost;
if(dist[e.to] > d2)
{
swap(dist[e.to], d2);
Q.push(P(dist[e.to], e.to));
}
if(dist2[e.to] > d2 && dist[v] < d2)
{
dist2[e.to] = d2;
Q.push(P(dist2[e.to], e.to));
}
}
}
printf("%lld\n", dist2[N]);
}
int main()
{
int A, B, D, t;
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &N, &R);
for(int i = 1; i <= N; i++) graph[i].clear();
for(int i = 0; i < R; i++)
{
scanf("%d%d%d", &A, &B, &D);
graph[A].push_back(edge(B, D));
graph[B].push_back(edge(A, D));
}
solve();
}
return 0;
}