Вы находитесь на странице: 1из 3

/* Title: prim.

cpp
* Abstract: Implements the Prim’s algorithm to calculate the minimum spanning tree (MST) from an input graph
* Author: Sergiy Zarubin
* ID: 1337
* Date: 06/16/2019
*/

#include <iostream>
#include <fstream>

using namespace std;

#define INF 9999999

struct graphMST {
int source;
int dist;
int cost;
};

void printGraph(graphMST* newGraph ,int size) {


for (int row = 0; row < size; row++){

cout<< newGraph[row].source<<" ";


cout<< newGraph[row].dist<<" ";
cout<< newGraph[row].cost<<endl;
}

}
void printMatrix (int** matrix,int size){

for (int row = 0; row < size; row++)


{
for (int col = 0; col < size; col++)
{
cout<<matrix[row][col]<<" ";
}
cout<<endl;
}
}

int main(){
/*Declaring variables*/
string fileName;
string line;

/*Get filename*/
cout << "Please enter file name: ";
getline(cin, fileName);

file:///C/Users/live/OneDrive/CSUMB/CST370/prim.txt[9/7/2019 6:07:30 PM]


/*If filename is not empty*/
if (!fileName.empty()){
try{
ifstream sampleFile;
sampleFile.open(fileName);
getline(sampleFile, line);
int no_nodes = stoi(line);

//Set selected nodes arraqy


bool* selected = new bool [no_nodes];

for(int i=0;i<no_nodes;i++){
selected[i] = false;
}

getline(sampleFile, line);
int no_edges = stoi(line);

//cout<<"Creating Matrix"<<endl;
int **matrix = new int* [no_edges];

for(int col = 0; col < no_edges; col++)


matrix[col] = new int[no_edges];

for (int row = 0; row < no_edges; row++)


{
for (int col = 0; col < no_edges; col++)
{
matrix[row][col] = 0;
}
}
//reading data
graphMST *newGraph = new (nothrow) graphMST[no_edges];

if (sampleFile.is_open()){
for (int row = 0; row < no_edges; row++){
sampleFile>> newGraph[row].source;
sampleFile>> newGraph[row].dist;
sampleFile>> newGraph[row].cost;
//ofset location by one
//and make it undirected
matrix[newGraph[row].source-1][newGraph[row].dist-1] = newGraph[row].cost;
matrix[newGraph[row].dist-1][newGraph[row].source-1] = newGraph[row].cost;
getline(sampleFile, line);
}
sampleFile.close();
}

//printGraph(newGraph,no_edges) ;
//printMatrix(matrix,no_edges);

int mst_edge = 0;
int first;

file:///C/Users/live/OneDrive/CSUMB/CST370/prim.txt[9/7/2019 6:07:30 PM]


cout<<"Enter the first vertex to start: ";
cin>>first;
selected[first-1]=true;

while (mst_edge<no_nodes-1){
int min = INF;
int x=0; int y=0;

for (int i=0; i<no_nodes; i++){


if(selected[i]){
for(int j = 0; j<no_nodes;j++){
if(!selected[j]&&matrix[i][j])
{
if(min>matrix[i][j]){
min = matrix[i][j];
x=i;y=j;

}
}
}
}
}

mst_edge++;
cout<<"("<<mst_edge<<") New edge: "<<x+1<<","<<y+1<<" – cost "<<matrix[x][y]<<endl;
selected[y] = true;

delete[] newGraph;
return 0;
}catch(exception const& e){
cout << "There was an error: " << e.what() << endl;
}

return 0;
}

file:///C/Users/live/OneDrive/CSUMB/CST370/prim.txt[9/7/2019 6:07:30 PM]

Вам также может понравиться