虽然快退役啦,还是留一个模板吧~
#include <cstdio> #include <cstring> #include <iostream> #include <queue> #include <map> #include <vector> using namespace std; const int maxn=100010; const int inf=0x3f3f3f3f; int n,m; struct node { int x,cost; }; vector<node> edge[100010]; int spfa(int s) { int vis[maxn]; int d[maxn]; queue<int> q; memset(vis,0,sizeof(vis)); fill(d,d+maxn,inf); vis[s]=1; // means s in the queue d[s]=0; q.push(s); // while(!q.empty()) { int now=q.front(); q.pop(); vis[now]=0; for(int i=0;i<edge[now].size();i++) { node temp=edge[now][i]; if(d[temp.x] > d[now]+temp.cost) { d[temp.x]=d[now]+temp.cost; if(vis[temp.x]==0) { vis[temp.x]=1; // q.push(temp.x); } } } } return d[n]; } int main() { while(cin>>n>>m) { if(n==0 || m==0) break; for(int i=0;i<=n;i++) edge[i].clear(); while(m--) { int a,b,cost; scanf("%d %d %d",&a,&b,&cost); node temp; temp.cost=cost; temp.x=a; edge[b].push_back(temp); temp.x=b; edge[a].push_back(temp); } cout<<spfa(1)<<endl; } return 0; }