输入包括多组数据。每组数据第一行是两个整数N、M(N<=100,M<=10000),N表示成都的大街上有几个路口,标号为1的路口是商店所在地,标号为N的路口是赛场所在地,M则表示在成都有几条路。N=M=0表示输入结束。接下来M行,每行包括3个整数A,B,C(1<=A,B<=N,1<=C<=1000),表示在路口A与路口B之间有一条路,我们的工作人员需要C分钟的时间走过这条路。 输入保证至少存在1条商店到赛场的路线。
Output
对于每组输入,输出一行,表示工作人员从商店走到赛场的最短时间
Sample Input
2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0
Sample Output
3 2
Source
UESTC 6th Programming Contest Online
代码:基于数组(时间复杂度为O(n^2))
1 #include<stdio.h>
2 #include<string.h>
3 const int inf=0x3f3f3f3f ;
4 int path[101];
5 int sta[101][101],lowcost[101];
6 void Dijkstra( int cost[][101], int n )
7 {
8 int i,j,min;
9 int vis[101]={1};
10 for(i=0; i<n ; i++)
11 {
12 lowcost[i]=cost[0][i];
13 path[i]=0;
14 }
15 lowcost[0]=0;
16 path[0]=-1;
17 int pre= 0;
18 for( i=1 ; i<n ;i++)
19 {
20 min=inf;
21 for(j=0 ; j<n ;j++)
22 {
23 if(vis[j]==0&&lowcost[pre]+cost[pre][j]<lowcost[j])
24 {
25 lowcost[j]=lowcost[pre]+cost[pre][j];
26 path[j]=pre;
27 }
28 }
29 for(j=0; j<n ;j++)
30 {
31 if(vis[j]==0&&lowcost[j]<min)
32 {
33 min=lowcost[j];
34 pre=j;
35 }
36 }
37 vis[pre]=1;
38 }
39 printf("%d\n",lowcost[n-1]);
40 }
41
42 int main()
43 {
44 int n,m,x,y,val,i,j;
45 while(scanf("%d%d",&n,&m),n+m)
46 {
47 for(i=0;i<n;i++)
48 {
49 for(j=0;j<n;j++)
50 {
51 sta[i][j]=inf;
52 }
53 }
54 while(m--)
55 {
56 scanf("%d%d%d",&x,&y,&val);
57 sta[y-1][x-1]=sta[x-1][y-1]=val;
58 }
59 Dijkstra(sta,n);
60 }
61 return 0;
62 }
采用以为数组,时间复杂度将为O(n*long(n));
代码:
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
const int inf=0x3f3f3f3f;
const int tol=101;
const int edg=10001;
int cost[edg],dist[tol]; /* <distance> */
int e,pnt[edg],nxt[edg],prev[tol],head[tol],vis[tol];
struct qnode{
int v ,c;
qnode(int vv=0 ,int cc=0):v(vv),c(cc){};
bool operator <(const qnode& r)const
{
return c>r.c;
}
};
void Dijkstra(int n , const int src) /* <src出发点> */
{
qnode mv ; //充当一个临时变量
int i,j,k,pre;
priority_queue<qnode>que ; /*<priority—>优先队列>*/
vis[src]=1;
dist[src]=0;
que.push( qnode(src,0) );
for( pre=src,i=1; i<n; i++)
{
for(j=head[pre] ; j!=-1 ;j=nxt[j])
{
k=pnt[j];
if(vis[k]==0&&dist[pre]+cost[j]<dist[k])
{
dist[k]=dist[pre]+cost[j];
que.push( qnode(pnt[j], dist[k]) );
prev[k]=pre;
}
}
while(!que.empty() && vis[que.top().v]==1)
{
que.pop();
}
if(que.empty())break;
mv=que.top();
que.pop();
pre=mv.v;
vis[pre]=1;
}
}
inline void addedge( int u ,int v,int c)
{
pnt[e]=v;
cost[e]=c;
nxt[e]=head[u];
head[u]=e++;
}
void init(int nv ,int ne)
{
int i,u,v;
int c;
e=0;
memset(head,-1,sizeof(head));
memset(vis,0,sizeof(vis));
memset(prev,-1,sizeof(prev));
for(i=0; i<nv ; i++)
dist[i]=inf;
for(i=0; i<ne ;i++)
{
scanf("%d%d%d",&u,&v,&c);
addedge(u-1,v-1,c);
addedge(v-1,u-1,c);
}
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m),n+m)
{
init(n,m);
Dijkstra(n,0);
printf("%d\n",dist[n-1]);
}
return 0;
}