本算法是对<算法导论>第25章第一节的实现
有三个版本:
第一个,普通版本:
//SLOW-ALL-PAIRS-SHORTEST-PATHS
#include<iostream>
using namespace std;
#define MAX 32767
int N,M;
int u,v,l;
int W[1000][1000],Q[1000][1000],tmp[1000][1000];
void print()
{
for(int i=0;i<N;++i)
{
for(int j=0;j<N;++j)
cout<<Q[i][j]<<"\t";
cout<<endl;
}
}
bool ExtendShortestPath()
{
bool sign=true;
for(int i=0;i<N;++i)
{
for(int j=0;j<N;++j)
{
for(int k=0;k<N;++k)
{
if(Q[i][k]<MAX&&W[k][j]<MAX)
{
if(Q[i][j]>Q[i][k]+W[k][j])
{
sign=false;
tmp[i][j]=Q[i][k]+W[k][j];
}
}
}
}
}
for(int i=0;i<N;++i)
for(int j=0;j<N;++j)
Q[i][j]=tmp[i][j];
return sign;
}
void SlowAllPairShortestPath()
{
bool getShortest=false;
while(!getShortest)
{
getShortest=ExtendShortestPath();
}
}
int main()
{
cin>>N>>M;
for(int i=0;i<N;++i)
{
for(int j=0;j<N;++j)
{
W[i][j]=Q[i][j]=tmp[i][j]=MAX;
}
W[i][i]=Q[i][i]=tmp[i][i]=0;
}
for(int i=0;i<M;++i)
{
cin>>u>>v>>l;
W[u-1][v-1]=Q[u-1][v-1]=tmp[u-1][v-1]=l;
}
SlowAllPairShortestPath();
print();
return 0;
}
第二个,高级一点,用到了指针交换技术:
<pre name="code" class="html">//SLOW-ALL-PAIRS-SHORTEST-PATHS
#include<iostream>
#include<fstream>
#include<algorithm>
using namespace std;
#define MAX 32767
ifstream fin("data.in");
int N,M;
int u,v,l;
int W[1000][1000],Q[1000][1000],tmp[1000][1000];
void print()
{
for(int i=0;i<N;++i)
{
for(int j=0;j<N;++j)
cout<<Q[i][j]<<"\t";
cout<<endl;
}
}
bool ExtendShortestPath()
{
bool sign=true;
for(int i=0;i<N;++i)
{
for(int j=0;j<N;++j)
{
for(int k=0;k<N;++k)
{
if(Q[i][j]>Q[i][k]+W[k][j])
{
sign=false;
tmp[i][j]=Q[i][k]+W[k][j];
}
else
tmp[i][j]=(tmp[i][j]<Q[i][j])?tmp[i][j]:Q[i][j];
}
}
}
swap(Q,tmp);
return sign;
}
void SlowAllPairShortestPath()
{
bool getShortest=false;
while(!getShortest)
{
getShortest=ExtendShortestPath();
}
}
int main()
{
cin>>N>>M;
for(int i=0;i<N;++i)
{
for(int j=0;j<N;++j)
{
W[i][j]=Q[i][j]=tmp[i][j]=MAX;
}
W[i][i]=Q[i][i]=tmp[i][i]=0;
}
for(int i=0;i<M;++i)
{
cin>>u>>v>>l;
W[u-1][v-1]=Q[u-1][v-1]=tmp[u-1][v-1]=l;
}
SlowAllPairShortestPath();
print();
return 0;
}
第三个,是另外一个版本:
这个只贴核心代码了
bool ExtendShortestPath()
{
bool sign=true;
for(int i=0;i<N;++i)
{
for(int j=0;j<N;++j)
{
for(int k=0;k<N;++k)
{
if(L[i][j]>L[i][k]+L[k][j])
{
sign=false;
tmp[i][j]=L[i][k]+L[k][j];
}
else
tmp[i][j]=(tmp[i][j]<=L[i][j])?tmp[i][j]:L[i][j];
}
}
}
swap(L,tmp);
return sign;
}
void FastAllPairShortestPath()
{
bool getShortest=false;
while(!getShortest)
{
getShortest=ExtendShortestPath();
}
}
这是算法导论上面伪代码的实现.P622