一道变相的FLOYD,想通以后还是蛮简单的,主要的难点是建图和更新两点之间的距离:
简要的说一下,建图的话就用MAP就好;
之后跟新两点之间的距离需要引入一个maxcost数组,用于标记两点之间的最大费用;这样一来更新规则就有了:
cost[i][j]-maxcost[i][j]>cost[i][k]+cost[k][j]-max(maxcost[i][k],maxcost[k][j]);
以下是代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<iostream>
#define INF 1000000
using namespace std;
char from[100],to[100];
char inputa[100],inputb[100];
int cost[105][105];
int maxcost[105][105];
int n,num;
map<string,int> judge;
void init()//初始化;
{
judge.clear();
for(int i=0;i<=100;i++)
{
for(int j=0;j<=100;j++)
{
maxcost[i][j]=0;
if(i==j) cost[i][j]=0;
else
cost[i][j]=INF;
}
}
}
void floyd()//算法主体
{
for(int k=1;k<=num;k++)
{
for(int i=1;i<=num;i++)
{
for(int j=1;j<=num;j++)
{
if(cost[i][j]-maxcost[i][j]>cost[i][k]+cost[k][j]-max(maxcost[i][k],maxcost[k][j]))//最为关键的跟新规则;
{
cost[i][j]=cost[i][k]+cost[k][j];
maxcost[i][j]=max(maxcost[i][k],maxcost[k][j]);
}
}
}
}
return ;
}
int main()
{
int c;
while(cin>>from>>to){
cin>>n;
init();
judge[from]=1;
judge[to]=2;
num=2;
for(int i=0;i<n;i++)
{
int a,b;
cin>>inputa>>inputb>>c;//建图
if(judge[inputa]==0)
{
judge[inputa]=++num;
}
if(judge[inputb]==0)
{
judge[inputb]=++num;
}
a=judge[inputa];
b=judge[inputb];
cost[a][b]=cost[b][a]=c;
maxcost[a][b]=maxcost[b][a]=c;
}
floyd();
printf("%d\n",cost[1][2]-maxcost[1][2]);//输出
}
return 0;
}