【洛谷1339 [USACO09OCT]】热浪Heat Wave 图论+最短路

时间:2022-04-11 11:03:12

AC代码

#include<bits/stdc++.h>
using namespace std;
const int MAXN=62000+10,INF=999999;
struct Edge{
int u,v,w,next;
}edge[MAXN];
int head[MAXN],n,m,s,t,dist[MAXN],cnt;
bool vis[MAXN];
void addedge(int x,int y,int z){
edge[cnt].u=x;
edge[cnt].v=y;
edge[cnt].w=z;
edge[cnt].next=head[x];
head[x]=cnt++;
}
void spfa(){
queue<int>q;
for(int i=1;i<=n;i++){
dist[i]=INF;
vis[i]=false;
}
dist[s]=0;
vis[s]=true;
q.push(s);
while(!q.empty()){
int k=q.front();
q.pop();
vis[k]=false;
for(int i=head[k];i!=-1;i=edge[i].next){
int to=edge[i].v;
if(dist[to]==INF||dist[to]>dist[k]+edge[i].w){
dist[to]=dist[k]+edge[i].w;
if(vis[to]==false){
vis[to]=true;
q.push(to);
}
}
}
}
}
int main()
{
memset(head,-1,sizeof(head));
scanf("%d%d%d%d",&n,&m,&s,&t);
for(int i=1;i<=m;i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
addedge(a,b,c);addedge(b,a,c);
}
spfa();
printf("%d",dist[t]);
return 0;
}