最短路问题,迪杰斯特拉,只不过判断最短距离时将等于情况也纳入进来,因为有可能到1号点的距离有好几个最小值,选择到上一个点距离最小的那个,因为前面的点都已经建好高铁了,从哪个点都可以到,选择距离最小的,开一个数组保存每一个点连接上一个点的最小距离,每次开头加上距离。
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=1e5+6,mod=1e9+7,INF=0x7f;
int ans,n,m;
struct edge
{
int to,weight;
}a[maxn];
struct node
{
int num,dist;
bool operator <(const node &x)const
{
return dist>x.dist;
}
};
vector<edge>g[maxn];
int d[maxn],vis[maxn];
void dij()
{
memset(a,INF,sizeof(a));
cin>>n>>m;
for(int i=0;i<m;i++)
{
int x,y,w;
cin>>x>>y>>w;
g[x].push_back(edge{y,w});//有向边,双向要写两次
g[y].push_back(edge{x,w});
}
memset(d,INF,sizeof(d));
d[1]=0;
priority_queue<node>q;
q.push(node{1,0});
a[1].weight=0;
while(!q.empty())
{
node t=q.top();
q.pop();
if(vis[t.num])
continue;
vis[t.num]=1;
ans+=a[t.num].weight;
//cout<<a[t.num].weight<<endl;
for(int i=0;i<g[t.num].size();i++)
{
edge e=g[t.num][i];
if(d[t.num]+e.weight<=d[e.to])
{
d[e.to]=d[t.num]+e.weight;
if(a[e.to].weight>=e.weight)
{a[e.to].to=t.num;a[e.to].weight=e.weight;}
q.push(node{e.to,d[e.to]});
}
}
}
}
int main()
{
dij();
cout<<ans<<endl;
return 0;
}