直接上例题:
原题链接(849. Dijkstra求最短路 I - AcWing题库)
ac代码:
#include <iostream>
#include <cstring>
#include <vector>
#include <utility>
#include <queue>
using namespace std;
const int V = 505;
typedef pair<int, int> PII;
vector<PII>rod[V];
int dis[V];//存储到该点的最短距离
bool vis[V];//用于标记是否已经找过该点
void dijk(int k)//k为起点
{
priority_queue<PII, vector<PII>, greater<PII> >que;//优先队列实现堆
memset(dis, 0x3f, sizeof(dis));//遍历之前保证所有点距离都很大
memset(vis, 0, sizeof(vis));//重置标记
dis[k] = 0;//到起点距离一定是0
que.push({ 0,k });//优先队列是pair类型,优先排first,避免写多余的函数所有把距离写前面,后面是点
while (que.size()) {
int tmp = que.top().second;//获得该点,至于first一定是当前最小的
que.pop();//已经得到点,出队
if (vis[tmp]) continue;//该点被标记过,跳过
vis[tmp] = 1;//没被标记的进行标记
for (int i = 0; i < rod[tmp].size(); i++) {//循环从队列取出的当前点距离其他点的距离
if (dis[rod[tmp][i].first] > (rod[tmp][i].second + dis[tmp])) {//当前点到点i的距离可被更新(更短)
dis[rod[tmp][i].first] = rod[tmp][i].second + dis[tmp];//进行更新
que.push({ dis[rod[tmp][i].first],rod[tmp][i].first });//将可以更新的点入队,rod[tmp][i]表示第i个点
}
}
}
}
int main()
{
int n, m;
int a, b, c;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
cin >> a >> b >> c;
rod[a].push_back({ b,c });
}
dijk(1);
if (dis[n] == 0x3f3f3f3f) dis[n] = -1;
cout << dis[n] << endl;
return 0;
}
可恶啊,vector不一定对,所以改板子吧
修改后的ac代码:(大体没变,只不过不用vector模拟实现)
#include <iostream>
#include <cstring>
#include <vector>
#include <utility>
#include <queue>
using namespace std;
const int N = 1e6 + 10;
typedef pair<int, int> PII;
int e[N], v[N], h[N], ne[N], cnt;
int dis[N];
bool vis[N];
int n, m, z;
void add(int a, int b, int c)
{
v[++cnt] = b, e[cnt] = c, ne[cnt] = h[a], h[a] = cnt;
}
void dijk(int s)
{
priority_queue<PII, vector<PII>, greater<PII> >que;
memset(dis, 0x3f, sizeof(dis));
memset(vis, 0, sizeof(vis));
dis[s] = 0;
que.push({ 0,s });
while (que.size()) {
int tmp = que.top().second;
que.pop();
if (vis[tmp]) continue;
vis[tmp] = 1;
for (int i = h[tmp]; i; i = ne[i]) {
if (dis[v[i]] > e[i] + dis[tmp]) {
dis[v[i]] = e[i] + dis[tmp];
que.push({ dis[v[i]],v[i] });
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
while (cin >> n >> m) {
if (n == 0 && m == 0) break;
cnt = 0;
memset(e, 0, sizeof(e));
memset(v, 0, sizeof(v));
memset(h, 0, sizeof(h));
memset(ne, 0, sizeof(ne));
for (int i = 1; i <= m; i++) {
int a, b, z;
cin >> a >> b >> z;
add(a, b, z);
//add(b, a, z);
}
dijk(1);
if(dis[n]==0x3f3f3f3f) cout<<"-1"<<endl;
else cout << dis[n] << endl;
}
}