A
#include<bits/stdc++.h>
using namespace std;
const int N=5e5+10,maxx= 2147483647;
typedef pair<int,int>pii;
int h[N],ne[N],e[N],w[N],idx;
int dist[N];
bool st[N];
int n,m,s;
void add(int a,int b,int c)
{
e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
void dijistra()
{
memset(dist,0x3f,sizeof dist);
dist[s]=0;
priority_queue<pii,vector<pii>,greater<pii>>q;
q.push({0,s});
while(!q.empty())
{
pii k=q.top();
q.pop();
int v=k.second,d=k.first;
if(st[v])continue;
st[v]=true;
for(int i=h[v];i!=-1;i=ne[i])
{
int j=e[i];
if(dist[j]>d+w[i])
{
dist[j]=d+w[i];
q.push({dist[j],j});
}
}
}
}
int main()
{
cin>>n>>m>>s;
memset(h,-1,sizeof h);
while(m--)
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
dijistra();
for(int i = 1; i <= n; i++)
{
if(dist[i] == 0x3f3f3f3f)
{
cout << maxx <<" ";
}
else
{
cout << dist[i] <<" ";
}
}
return 0;
}
B
堆优化
#include<bits/stdc++.h>
using namespace std;
const int maxx = 2e5 + 100;
int h[maxx], ne[maxx], idx, e[maxx],w[maxx],dist[maxx];
int n, m, s;
bool st[maxx];
typedef pair<int, int>pll;
void dijistra()
{
memset(dist, 0x3f3f3f3f, sizeof dist);
priority_queue<pll, vector<pll>, greater<pll>>q;
dist[s] = 0;
q.push({ 0,s });
while (q.size())
{
auto t = q.top();
q.pop();
int d = t.first, num = t.second;
if (st[num])continue;
st[num] = true;
for (int i = h[num]; i != -1; i = ne[i])
{
int j = e[i];
if (dist[j] > dist[num] + w[i])
{
dist[j] = dist[num] + w[i];
q.push({ dist[j],j });
}
}
}
}
void add(int a, int b, int c)
{
e[idx] = b, ne[idx] = h[a], w[idx] = c,h[a]=idx++;
}
int main()
{
cin >> n >> m >> s;
memset(h, -1, sizeof h);
while (m--)
{
int x, y, z;
cin >> x >> y >> z;
add(x, y, z);
}
dijistra();
for (int i = 1; i <= n; i++)
{
cout << dist[i] << " ";
}
return 0;
}
C
因为是无向图,add(x, y, z);
add(y ,x, z);
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int maxx = 150010;
typedef pair<int, int>PII;
int h[maxx], w[maxx], ne[maxx], e[maxx], dist[maxx], idx;
bool st[maxx];
int n, m,s,t;
void add(int a, int b, int c)
{
e[idx] = b;
ne[idx] = h[a];
w[idx] = c;
h[a] = idx++;
}
int di()
{
memset(dist, 0x3f, sizeof dist);
dist[s] = 0;
priority_queue<PII, vector<PII>, greater<PII>>q;
q.push({ 0,s });
while (q.size())
{
PII k = q.top();
q.pop();
int ver = k.second, d = k.first;
if (st[ver])continue;
st[ver] = true;
for (int i = h[ver]; i != -1; i = ne[i])
{
int j = e[i];
if (dist[j] > d + w[i])
{
dist[j] = d + w[i];
q.push({ dist[j],j });
}
}
}
return dist[t];
}
int main()
{
memset(h, -1, sizeof h);
cin >> n >> m>> s >> t;
while (m--)
{
int x, y, z;
cin >> x >> y >> z;
add(x, y, z);
add(y ,x, z);
}
cout << di() << endl;
return 0;
}