///////////////////////////////////////////////////////////////////////////////Dijkstra, 不能解决含负权值边的图
#include<iostream>
#include<queue>
#include<stack>
#include<cstring>
using namespace std;
int main()
{
int weight[5][5]={{0,50,-1,80,-1},
{-1,0,60,90,-1},
{-1,-1,0,-1,40},
{-1,-1,20,0,70},
{-1,50,-1,-1,0}};
int parentV[5]={0};
int min[5];
for(int i=0;i<5;i++)
min[i]=10000;
char v[5]={‘A’,’B’,’C’,’D’,’E’};
queue<int> nextV;
stack<int> routeV;
int usedV[5]={0};
int currentV;
nextV.push(0);
min[0]=0;
while(!nextV.empty())
{
currentV=nextV.front();
nextV.pop();
for(int i=0;i<5;i++)
{
if(weight[currentV][i]>0)
{
if(min[currentV]+weight[currentV][i]<min[i])
{
min[i]=min[currentV]+weight[currentV][i];
parentV[i]=currentV;
}
if(usedV[i]==0)
{
nextV.push(i);
usedV[i]=1;
}
}
}
}
cout << “Shortest route:” << endl;
for(int i=1;i<5;i++)
{
cout << “A->” << v[i] << “: ” << min[i] << “, “;
int routeI=i;
while(parentV[routeI]!=0)
{
routeV.push(parentV[routeI]);
routeI=parentV[routeI];
}
cout << “A”;
while(!routeV.empty())
{
cout << “->” << v[routeV.top()];
routeV.pop();
}
cout << “->” << v[i] << endl;
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////Bellman-ford,不能解决含负权值回路的图
#include<iostream>
#include<stack>
#define INF 999999
using namespace std;
int main()
{
int weight[7][7]={{0,6,5,5,INF,INF,INF},
{INF,0,INF,INF,-1,INF,INF},
{INF,-2,0,INF,1,INF,INF},
{INF,INF,-2,0,INF,-1,INF},
{INF,INF,INF,INF,0,INF,3},
{INF,INF,INF,INF,INF,0,3},
{INF,INF,INF,INF,INF,INF,0}};
//cout << sizeof(int) << INF;
int dist[7][7];
stack<int> routeV;
int parentV[7];
int minJ=INF,minParent;
for(int i=0;i<7;i++)
{
dist[1][i]=weight[0][i];
parentV[i]=0;
}
for(int k=2;k<7;k++)
{
for(int j=0;j<7;j++)
{
for(int m=0;m<7;m++)
{
if(m!=j)
{
if(dist[k-1][m]+weight[m][j]<minJ)
{
minJ=dist[k-1][m]+weight[m][j];
minParent=m;
}
}
}
if(minJ<dist[k-1][j])
{
dist[k][j]=minJ;
parentV[j]=minParent;
}
else
{
dist[k][j]=dist[k-1][j];
}
minJ=INF;
}
}
cout << “Shortest route: ” << endl;
for(int i=1;i<7;i++)
{
cout << “0->” << i << ” : “;
cout << dist[6][i] << “, “;
int routeI=i;
while(parentV[routeI]!=0)
{
routeV.push(parentV[routeI]);
routeI=parentV[routeI];
}
cout << “0”;
while(!routeV.empty())
{
cout << “->” << routeV.top();
routeV.pop();
}
cout << “->” << i << endl;
}
return 0;
}