poj 2387 Til the Cows Come Home
#include <iostream> //单源顶点最短路径:迪杰斯特拉(Dijkstra)算法
using namespace std;
const int MaxWeight=1000002; //最大值应该是1000*100+1
int Vertex,edge[1002][1002],distD[1002],i,j;
void init()
{
for(i=1;i<=Vertex;i++) //结点坐标都是从1开始的
for(j=1;j<=Vertex;j++)
{
if(i==j)
edge[i][j]=0;
else
edge[i][j]=MaxWeight;
}
}
void ShortestPath_Dijstra(int v) //从源点v到其余各顶点的最短路径长度
{
int min,u,S[1002],pathD[1002];
for(i=1;i<=Vertex;i++)
{
distD[i]=edge[v][i];S[i]=0;
if(i!=v&&distD[i]<MaxWeight)
pathD[i]=v;
else
pathD[i]=-1;
}
S[v]=1;
for(i=1;i<Vertex;i++)
{
min=MaxWeight;
for(j=1;j<=Vertex;j++)
if(!S[j]&&distD[j]<min)
{
u=j;min=distD[j];
}
S[u]=1;
for(j=1;j<=Vertex;j++)
if(!S[j]&&edge[u][j]<MaxWeight&&distD[u]+edge[u][j]<distD[j])
{
distD[j]=distD[u]+edge[u][j];pathD[j]=u;
}
}
printf("%d\n",distD[1]);
}
int main()
{
int t,a,b,c;
cin>>t>>Vertex;
init();
while(t--)
{
cin>>a>>b>>c;
if(edge[a][b]>c) //有重边
edge[a][b]=edge[b][a]=c;
}
ShortestPath_Dijstra(Vertex);
return 0;
}