Sei sulla pagina 1di 2

1 /*

2 * Title: prim.cpp
3 * Abstract: This program will determine the MST by using Prim's Algorithm
4 * Author: William Baker
5 * ID: 1235
6 * Date: 06/18/2019
7 */
8
9 #include <iostream>
10 #include <new>
11 #include <fstream>
12 #include <cstring>
13 #include <sstream>
14 #include <string>
15 #include <stdio.h>
16 #include <string.h>
17
18 using namespace std;
19
20 int main () {
21 string value, str, row, index, str2;
22 int length, n, vertices, edges, flag;
23 int minValue = 0;
24 int count = 0;
25 int front, start;
26
27 cout << "Enter input file name: ";
28 cin >> str;
29 cout << "Enter a start vertex: ";
30 cin >> str2;
31 cout << "\n";
32 start = stoi(str2);
33 ifstream myfile (str);
34 if (myfile.is_open())
35 {
36 getline(myfile, value);
37 vertices = stoi(value);
38 //cout << vertices;
39
40 getline(myfile, value);
41 edges = stoi(value);
42 //cout<< edges;
43
44 length = (edges * 3);
45
46 int * list;
47 list = new int[length];
48
49 int i = 0;
50
51 while ( getline (myfile, value) )
52 {
53 //cout << "test";
54 stringstream ss(value);
55 string token;
56
57 while(getline(ss, index, ' ')){
58 // cout << index << "\n";
59 //cout << token;
60 list[i] = stoi(index);
61 i++;
62 }
63 }
64
65 int * visited;
66 visited = new int[vertices];
67 visited[0] = start;
68
69 int visitedCount = 1;
70
71 for(int i=1; i < vertices; i++){
72 int max = -1;
73 int maxIndex, offset;
74 for(int j = 0; j<visitedCount; j++){
75 for(int k=0; k<edges; k++){
76
77 if(list[k*3] == visited[j]){
78 //cout<< "test" << visited[j];
79 flag = -1;
80 for(int x =0; x<visitedCount; x++){
81 //cout <<"\nVisited Count: " << visited[x] << "\n";
82 if (list[k*3+1] == visited[x]){
83 flag = 1;
84
85 }
86 }
87 if((list[k*3 +2] < max || max==-1) && flag<0){
88 maxIndex= k*3;
89 max = list[maxIndex + 2];
90 offset = 1;
91 // cout <<"\nMax Index: " << maxIndex << "\n";
92 }
93 }
94
95 if(list[k*3 + 1] == visited[j]){
96 //cout<< "test" << visited[j];
97 flag = -1;
98 for(int x =0; x<visitedCount; x++){
99 //cout <<"\nVisited Count: " << visited[x] << "\n";
100 if (list[k*3] == visited[x]){
101 flag = 1;
102 }
103 }
104 if((list[k*3 +2] < max || max==-1) && flag<0){
105 maxIndex= k*3;
106 max = list[maxIndex + 2];
107 offset = 0;
108 // cout <<"\nMax Index: " << maxIndex << "\n";
109 }
110 }
111 }
112 }
113 visited[i] = list[maxIndex + offset];
114 visitedCount++;
115 cout << "New edge: " << list[maxIndex] << ", " << list[maxIndex + 1] << " -
cost " << list[maxIndex + 2] << "\n";
116 }
117
118
119 //***************************************************************************************
*****************
120 }
121 }

Potrebbero piacerti anche