最短路模板(前向星)
#include<iostream> #include<algorithm> #include<cstring> #include<queue> const int maxn=100005; const int inf=999999; using namespace std; struct Edge { int next; int to; int w; }edge[maxn]; struct node { int num; int dist; node(int _num=0,int _dist=0):num(_num),dist(_dist){} friend bool operator<(node a,node b) { return a.dist>b.dist; } }; int head[maxn]; int s[maxn]; int n,m,cnt; int dis[maxn]; bool vis[maxn]; void add(int u,int v,int w) { edge[cnt].next=head[u]; edge[cnt].to=v; edge[cnt].w=w; head[u]=cnt++; } void dij(int x) { priority_queue<node>que; memset(dis,0x3f,sizeof(dis)); memset(vis,0,sizeof(vis)); dis[x]=0; que.push(node(x,0)); while(!que.empty()) { node p=que.top(); que.pop(); int now=p.num; for(int i=head[now];i!=-1;i=edge[i].next) { Edge e=edge[i]; if(dis[e.to]>dis[now]+e.w) { dis[e.to]=dis[now]+e.w; que.push(node(e.to,dis[e.to])); } } } } int main() { int x,y,w; while(cin>>n>>m) { cnt=0; memset(head,-1,sizeof(head)); for(int i=1;i<=m;i++) { cin>>x>>y>>w; add(x,y,w); } dij(1); cout<<dis[9]<<endl; } return 0; }