入门题:
poj 2387(单源最短路径)-------dijkstra模板题o(n^2)
但是需要注意题中是可以存在重边的,所以需要判断cost[i][j]>w时cost[i][j]=w 在这里wa过几次

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
const int MAXN=1010;
//***************************************************************
//Dijkstra-数组实现O(n^2)
//单源最短路径
//lowcost[]---从点beg到其他点的距离
//不记录路径
//结点编号从1开始的
//****************************************************************
#define INF 0x3f3f3f3f //这个无穷大不能太大,防止后面溢出
#define typec int
bool vis[MAXN];
void Dijkstra(typec cost[][MAXN],typec lowcost[MAXN],int n,int beg)
{
typec minc;
int i,j,w;
memset(vis,false,sizeof(vis));
vis[beg]=true;
for(i=1;i<=n;i++)
lowcost[i]=cost[beg][i];
lowcost[beg]=0;
for(i=1;i<n;i++)
{
minc=INF;
for(j=1;j<=n;j++)
if(!vis[j]&&lowcost[j]<minc)
{
minc=lowcost[j];
w=j;
}
if(minc>=INF)break;
vis[w]=true;
for(j=1;j<=n;j++)
if(!vis[j]&&lowcost[w]+cost[w][j]<lowcost[j])
lowcost[j]=lowcost[w]+cost[w][j];
}
}
//**************************************************************
int cost[MAXN][MAXN];
int dist[MAXN];
int main()
{
int m,n;
scanf("%d%d",&m,&n);//m条边,n个点
for(int i=1;i<=n;i++)//初始化路径值
for(int j=1;j<=n;j++)
{
if(i==j)cost[i][j]=0;
else cost[i][j]=INF;
}
int a,b,c;
for(int i=1;i<=m;i++){
cin>>a>>b>>c;//a点到b点的路径长为c
if(c<cost[a][b])//重边---选择最短的边
cost[a][b]=cost[b][a]=c;
}
Dijkstra(cost,dist,n,n);//数组的大小为n,起点为n
if(dist[n]>=INF)printf("-1\n");
else printf("%d\n",dist[1]);
return 0;
}
