用迪杰斯特拉或者flyod皆可。
传送门:http://acm.hdu.edu.cn/showproblem.php?pid=2544
迪杰斯特拉版本:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const int MAXN=105;
const int INF=0x3f3f3f3f;
bool vis[MAXN];
int pre[MAXN];
int cost[MAXN][MAXN];
int lowcost[MAXN];
void Init(){
memset(cost,0x3f,sizeof(cost));
}
void Dijkstra(int n,int beg){
for(int i=0;i<n;i++){
lowcost[i]=INF;vis[i]=false;pre[i]=-1;
}
lowcost[beg]=0;
for(int j=0;j<n;j++){
int k=-1;
int Min=INF;
for(int i=0;i<n;i++){
if(!vis[i]&&lowcost[i]<Min){
Min=lowcost[i];
k=i;
}
}
if(k==-1)break;
vis[k]=true;
for(int i=0;i<n;i++){
if(!vis[i]&&lowcost[k]+cost[k][i]<lowcost[i]){
lowcost[i]=lowcost[k]+cost[k][i];
pre[i]=k;
}
}
}
}
void Debug_cost(int n){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
printf("%d ",cost[i][j]);
}
printf("\n");
}
}
void Input(){
int n,m;
while(scanf("%d %d",&n,&m),n+m){
int tempa,tempb,tempr;
Init();
for(int i=0;i<m;i++){
scanf("%d %d %d",&tempa,&tempb,&tempr);
tempa --; tempb --;
if(cost[tempa][tempb]>tempr){
cost[tempa][tempb] = tempr;
cost[tempb][tempa] = tempr;
}
}
//Debug_cost(n);
Dijkstra(n,0);
printf("%d\n",lowcost[n-1]);
}
}
void File(){
freopen("a.in","r",stdin);
freopen("a.out","w",stdout);
}
int main(void){
// File();
Input();
return 0;
}
flyod版本:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int d[105][105];
void Input(){
int n,m;
while(scanf("%d %d",&n,&m),n+m){
int tempa,tempb,tempr;
memset(d,0x3f,sizeof(d));
for(int i=0;i<m;i++){
scanf("%d %d %d",&tempa,&tempb,&tempr);
tempa --;tempb--;
if(d[tempa][tempb]>tempr){
d[tempa][tempb] = tempr;
d[tempb][tempa] = tempr;
}
}
for(int k=0;k<n;k++){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(d[i][j]>d[i][k]+d[k][j]){
d[i][j] = d[i][k] + d[k][j];
}
}
}
}
printf("%d\n",d[0][n-1]);
}
}
void File(){
freopen("a.in","r",stdin);
freopen("a.out","w",stdout);
}
int main(void){
// File();
Input();
return 0;
}