最直接的Dijkstra,最短路Dijkstra算法模板。
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<string>
#include<map>
#include<set>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<sstream>
#define ll long long
using namespace std;
/**********************************************************/
const int N_MAX = 100+10;
const int INF = 0x00ffffff;
const double M_DBL_MAX = 1.7976931348623158e+308;
const double M_DBL_MIN = 2.2250738585072014e-308;
int n;
int maps[N_MAX][N_MAX];
int d[N_MAX],vis[N_MAX];
/**********************************************************/
int min_2 (int x,int y) {return x<y?x:y;}
int max_2 (int x,int y) {return x>y?x:y;}
void dijkstra ();
/**********************************************************/
int main()
{
//freopen ("in.txt","r",stdin);
while(scanf ("%d",&n)!=EOF)
{
memset (maps,0,sizeof (maps));
char s[N_MAX];
for (int i=1;i<n;i++)
for (int j=0;j<i;j++){
scanf ("%s",s);
if (s[0]=='x') maps[i][j]=maps[j][i]=INF;
else maps[i][j]=maps[j][i]=atoi(s);
}
dijkstra ();
int m=0;
for (int i=0;i<n;i++)
m=(m<d[i]?d[i]:m);
printf ("%d\n",m);
}
return 0;
}
void dijkstra ()
{
memset (vis,0,sizeof (vis));
for (int i=0;i<n;i++)
d[i]=(i==0?0:INF);//注意初始化
for (int i=0;i<n;i++){//循环n次
int x,m=INF;
for (int y=0;y<n;y++)//寻找d值最小的结点x
if (!vis[y]&&d[y]<m)
m=d[x=y];//更新最小结点的下标x
vis[x]=1;
for(int y=0;y<n;y++)
d[y]=min_2 (d[y],d[x]+maps[x][y]);//遍历和x有路的所有结点y,更新d[y]
}
}