dijkstra算法–邻接矩阵
#include<iostream>
#include<cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 2510;
int g[N][N], d[N];
bool s[N];
int main()
{
int n, m, t1, t2;
cin >> n >> m >> t1 >> t2;
memset(g, 0x3f, sizeof(g));
memset(d, 0x3f, sizeof(d));
for(int i = 1; i <= m; i++)
{
int a, b, c;
cin >> a >> b >> c;
g[a][b] = c;
g[b][a] = c;
}
d[t1] = 0;
for(int i = 0; i < n; i++)
{
int t = -1;
for(int j = 1; j <= n; j++)
{
if(!s[j] && (t == -1 || d[t] > d[j])) t = j;
}
s[t] = true;
for(int j = 1; j <= n; j++)
{
d[j] = min(d[j], d[t] + g[t][j]);
}
}
cout << d[t2] << endl;
return 0;
}
dijkstra算法–邻接表
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 6210 * 2;
int h[N], ne[N], e[N], w[N], d[N], idx = 0;
bool s[N];
// struct cmp{
// bool operator()(const PII a, const PII b)
// {
// return a.first < b.first;
// }
// };
priority_queue<PII, vector<PII>, greater<PII> > p;
void add(int a, int b, int c)
{
e[idx] = b; w[idx] = c;
ne[idx] = h[a]; h[a] = idx++;
}
int main()
{
int n, m, t1, t2;
memset(h, -1, sizeof(h));
cin >> n >> m >> t1 >> t2;
while(m--)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
add(b, a, c);
}
memset(d, 0x3f, sizeof(d));
d[t1] = 0;
PII x;
x.first = 0;
x.second = t1;
p.push(x);
while(p.size())
{
int dist = p.top().first;
int ver = p.top().second;
p.pop();
if(s[ver]) continue;
s[ver] = true;
for(int i = h[ver]; i != -1; i = ne[i])
{
int j = e[i];
if(d[j] > dist + w[i])
{
d[j] = dist + w[i];
p.push({d[j], j});
}
}
}
cout << d[t2] << endl;
return 0;
}