参考挑战程序设计竞赛(第2版)——人民邮电出版社中的写法
Dijkstra
#include<iostream>
using namespace std;
#define MAX_V 10
#define INF 9999
int main() {
int cost[MAX_V][MAX_V] = { 0 };
int d[MAX_V] = { 0 };
bool used[MAX_V] = { false };
int V = 0;
cout << "输入顶点个数:" << " ";
cin >> V;
for (int i = 0; i < V; i++)
{
d[i] = INF;
//cout << d[i] << "/ ";
//cout << used[i] << " ";
}
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
cout << "邻接表第" << i + 1 << "行,第" << j + 1<< "列:";
cin >> cost[i][j];
}
}
cout << "输入源点s:" << " ";
int s = 0;
cin >> s;
d[s] = 0;
while (true)
{
int v = -1;
for (int i = 0; i < V; i++)
{
if (!used[i]&&(v==-1||d[i]<d[v]))
{
v = i;//在没有选过的定点中选中权值最小的
}
}
if (v==-1)
{
break;//所有的顶点都已经走过了
}
used[v] = true;//这个顶点被选中了
cout << "选中了顶点" << v << " ";
for (int i = 0; i < V; i++)
{
if (d[v]+cost[v][i]<d[i])
{
d[i] = d[v] + cost[v][i];//有了新加入的顶点,重新寻找最小路径
}
}
}
for (int i = 0; i < V; i++)
{
cout << "顶点" << i << ":" << d[i] << " ";
}
return 0;
}
prim
#include<iostream>
using namespace std;
#define MAX_V 10
#define INF 9999
int main() {
int cost[MAX_V][MAX_V] = { 0 };
int mincost[MAX_V] = { 0 };
bool used[MAX_V] = { false };
int V = 0;
cout << "输入顶点个数:" << " ";
cin >> V;
for (int i = 0; i < V; i++)
{
mincost[i] = INF;
used[i] = false;
//cout << d[i] << "/ ";
//cout << used[i] << " ";
}
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
cout << "邻接表第" << i + 1 << "行,第" << j + 1 << "列:";
cin >> cost[i][j];
}
}
int len = 0;
mincost[0] = 0;
while (true)
{
int v = -1;
for (int i = 0; i < V; i++)
{
if (!used[i] && (v == -1 || mincost[i] < mincost[v]))
{
v = i;//在没有选过的定点中选中权值最小的
}
}
if (v == -1)
{
break;//所有的顶点都已经走过了
}
used[v] = true;//这个顶点被选中了
cout << "选中了顶点" << v << " ";
len += mincost[v];
for (int i = 0; i < V; i++)
{
if (cost[v][i] < mincost[i])
{
mincost[i] = cost[v][i];//有了新加入的顶点,重新寻找最小路径
}
}
}
for (int i = 0; i < V; i++)
{
cout << "顶点" << i << ":" << mincost[i] << " ";
}
cout <<"总长"<< len << endl;
return 0;
}
多源最短路径
#include<iostream>
using namespace std;
#define MAX_V 10
#define INF 9999
int main() {
int cost[MAX_V][MAX_V] = { 0 };
int V = 0;
cout << "输入顶点个数:" << " ";
cin >> V;
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
cout << "邻接表第" << i + 1 << "行,第" << j + 1 << "列:";
cin >> cost[i][j];
}
}
for (int k = 0; k < V; k++)
{
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
if (cost[i][j]>cost[i][k]+cost[k][j])
{
cost[i][j] = cost[i][k] + cost[k][j];
}
}
}
}
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
cout<< cost[i][j] << " ";
}
cout << "\n";
}
return 0;
}