#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<queue>
#include<stack>
#define OK 0
#define ERROR 1
#define MAXSIZE 1000
using namespace std;
typedef int ElemType;
FILE *fp;
void InitFile()
{
bool e;
fopen_s(&fp, "data.txt", "r");
if (!fp) exit(ERROR);
return;
}
typedef bool Status;
单源最短路径 Dijkstra
/******
file input:
*******/
/*typedef struct node
{
int vertex;
struct node *link;
}Node, *node_ptr;*/
//node_ptr vertex;
#define MAX_VERTICES 6
#define MAX_VALUE 1000
int mydistance[MAX_VERTICES];
int found[MAX_VERTICES];
int cost[][MAX_VERTICES] =
{
0, 50, 10, MAX_VALUE, 45, MAX_VALUE,
MAX_VALUE, 0, 15, MAX_VALUE, 10, MAX_VALUE,
20, MAX_VALUE, 0, 15, MAX_VALUE, MAX_VALUE,
MAX_VALUE, 20, MAX_VALUE, 0, 35, MAX_VALUE,
MAX_VALUE, MAX_VALUE, 30, MAX_VALUE, 0, MAX_VALUE,
MAX_VALUE, MAX_VALUE, MAX_VALUE, 3, MAX_VALUE, 0
};
;
int choose(int mydistance[], int n, int found[])//选择最小代价的边
{
int i, min, minpos;
min = MAX_VALUE;
minpos = -1;
for (i = 0; i < MAX_VERTICES; i++)
{
if (mydistance[i] < min && !found[i])
{
min = mydistance[i];
minpos = i;
}
}
return minpos;
}
//单源最短路径
void shorteatpath(int v, int cost[][MAX_VERTICES], int mydistance[], int n, int found[])
{
int i, u, w;
for (i = 0; i < MAX_VERTICES; i++){ found[i] = 0; mydistance[i] = cost[v][i]; }
found[v] = 1;
mydistance[v] = 0;
for (i = 0; i < n-1; i++)// i<n-2 为什么
{
u = choose(mydistance, n, found);
if (u < 0) continue;/
found[u] = 1;
for (w = 0; w < n; w++)
{
if (!found[w])
if (mydistance[u] + cost[u][w] < mydistance[w])
mydistance[w] = mydistance[u] + cost[u][w];
}
}
}
//by zhaoyang @ 2014.4.20
int main()
{
//InitFile();;
for (int j = 0; j < MAX_VERTICES; j++)
{
printf("%d:\t", j);
//for (int i = 0; i < MAX_VERTICES; i++) found[i] = 0;
shorteatpath(j, cost, mydistance, MAX_VERTICES, found);
for (int i = 0; i < MAX_VERTICES; i++)
if (mydistance[i] != MAX_VALUE)
printf("%d %d\t", i, mydistance[i]);
else printf("%d \t", i);
printf("\n");
}
//fclose(fp);
return 0;
}
25.单源最短路径 Dijkstra
最新推荐文章于 2023-10-17 21:14:40 发布