1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include<iostream> using namespace std; int Max = 100; void djstr(int** a, int v, int e) { int* p = new int[v]; int* d = new int[v];
int s = 0; bool* label = new bool[v]; for (int i = 0; i < v; i++) label[i] = false;
for (int i = 0; i < v; i++) if (a[0][i] > 0) { p[i] = 0; d[i] = a[0][i]; } else { p[i] = -1; d[i] = Max; } label[0] = true; while (s < v) { int index=0, min=d[0]; for(int i=0;i<v;i++) if (!label[i]&&d[i] < min) { min = d[i]; index = i; } ++s; label[index] = true; for (int i = 0; i < v; i++) { if (a[index][i] + d[index] < d[i]) { d[i] = a[index][i] + d[index]; p[i] = index; } } } d[0] = 0; for (int i = 0; i < v; i++) cout << d[i] << " "; cout << endl; for (int i = 0; i < v; i++) cout << p[i]+1 << " "; } int main() { int v = 5; int e = 7; int b[5][5] = { { 0,4,2,Max,8 }, { Max,0,Max,4,5 }, { Max,Max,0,1,Max }, { Max,Max,Max,0,3 }, { Max,Max,Max,Max,0 } }; int** a = new int*[v]; for (int i = 0; i < v; i++) { a[i] = new int[v]; for (int j = 0; j < v; j++) a[i][j] = b[i][j]; } djstr(a, v, e); system("pause"); return 0; }
|