2
懂得迪杰斯特拉算法就不难,看备注应该就懂了
# include <stdio.h> # include <string.h> # include <algorithm> using namespace std; const int inf=2000000000; int g[110][110]; int d[110]; int vis[110]; int main(){ int n, m, i, j, k, temp; int num1, num2, num3; while(scanf("%d%d", &n, &m)){ if(m==0&&n==0){ break; } memset(g, 0, sizeof(g)); for(i=1; i<=m; i++){ scanf("%d%d%d", &num1, &num2, &num3); g[num1][num2]=g[num2][num1]=num3;//做无向图处理 } memset(vis, 0, sizeof(vis));//每个节点是否确定最小值,已确定则为1 for(i=1; i<=n; i++){//初始化距离,d[i]表示i到1的最短路径距离 d[i]=(i==1?0:inf); } for(j=1; j<n; j++){ int x, m=inf; for(k=1; k<=n; k++){ if(!vis[k]&&d[k]<m){//寻找未确定最短路的点中的的d最小值,视为当前点的最短路 m=d[x=k]; } } vis[x]=1; for(k=1; k<=n; k++){//从找到的点出发更新最小值 if(g[x][k]) d[k]=min(d[k], d[x]+g[x][k]); } } printf("%d\n", d[n]); } return 0; }
下面上一下优先队列版的:
AC代码:
# include <cstdio> # include <queue> # include <vector> using namespace std; const int inf=2000000000; struct p{ int u, d; bool operator < (const p& rsh)const{ return d>rsh.d; } }; priority_queue<p> q; struct edge{ int to; int cost; }; vector<edge> g[110]; int d[110]; int main(){ int n, m, i, j, k, num1, num2, num3; edge a; p temp; while(scanf("%d%d",&n, &m)){ if(n==0&&m==0){ break; } for(i=2; i<=n; i++){ d[i]=inf; } d[1]=0; for(i=1; i<=n; i++){ g[i].clear(); } for(i=1; i<=m; i++){ scanf("%d%d%d", &num1, &num2, &num3); a.to=num2;a.cost=num3; g[num1].push_back(a); a.to=num1;a.cost=num3; g[num2].push_back(a); } while(!q.empty()){ q.pop(); } temp.d=0;temp.u=1; q.push(temp); while(!q.empty()){ temp=q.top();q.pop(); int x=temp.u; if(temp.d>d[x]){ continue; } for(i=0; i<=g[x].size()-1; i++){ a=g[x][i]; if(d[a.to]>d[x]+a.cost){ d[a.to]=d[x]+a.cost; temp.d=d[a.to]; temp.u=a.to; q.push(temp); } } } printf("%d\n", d[n]); } return 0; }