So what this code is trying to do is read a .dat file that has 3 columns the first two are numbers that represent cities and the third is the cost of a cable that is connected between them. It will read the file and then find the cheapest cost that has all cities connected some way or form.
My Code:
- Code: Select all
#include <iostream>
#include <time.h>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
class Cable{ public: int city1, city2, cost; bool solution; };
int costcompare(const void *x, const void *y) {
if ((**(Cable **)x).cost < (**(Cable**)y).cost) return -1;
if ((**(Cable **)x).cost > (**(Cable**)y).cost) return 1;
return 0;
}
class Solver {
Cable **cables;
int ncables;
int ncities;
int *group;
Cable **argv;
int sum;
int dummy;
string buffer;
fstream *fin;
public:
//constructor
Solver() {
this->ncables = ncables;
this->ncities = ncities;
this->sum = sum;
this->dummy = dummy;
this->buffer = buffer;
this->cables = cables;
this->group = group;
this->fin = fin;
this->argv = argv;
}
//reads the file from main
void readFile(char **argv) {
fstream *fin = new fstream(argv[1], ios::in);
if (fin->fail()) {
cerr << "Cannot open file " << argv[1] << "\n";
exit(0);
}
while (getline(*fin, buffer)) ncables++;
fin->close();
fin->clear();
Cable *cables = new Cable[ncables];
int sum = 0;
fin->open(argv[1], ios::in);
for (int i = 0; i < ncables; i++) {
//cables[i] = new Cable();
*fin >> cables[i].city1>> cables[i].city2 >> cables[i].cost;
sum += cables[i].cost;
}
fin->close();
fin->clear();
}
// Finds the number of cities
void findNcity () {
int ncities = 0;
for (int i=0; i < ncables; i++) {
if (cables[i]->city1 > ncities) ncities = cables[i]->city1;
if (cables[i]->city2 > ncities) ncities = cables[i]->city2;
}
}
//gives the group their numbers
void giveGroupnum() {
int *group = new int[ncities + 1];
for (int i=0; i <= ncities; i++) group[i] = i;
}
//the cycle
bool isCycle(Cable *cable) {
if (group[cable->city1] == group[cable->city2]) return false;
int dummy = group[cable->city2];
for (int i = 0; i <= ncities; i++)
if (group[i] == dummy) group[i] = group[cable->city1];
return true;
}
//Solves the problem
void solve() {
qsort(cables, ncables, sizeof(Cable*), costcompare);
for (int i=0; i < ncables; i++) {
if (isCycle(cables[i])) cables[i]->solution = true;
else cables[i]->solution = false;
}
for (int i=0; i < ncables; i++){
if (cables[i]->solution == true)
cout << i << ": " << cables[i]->city1 << " "
<< cables[i]->city2 << " "
<< cables[i]->cost << "\n"; }
}
};
int main(int argc, char **argv)
{
if (argc != 2) {
cout << "\nUsage: " << argv[0] << " \n";
exit (0);
}
Solver mysolver;
mysolver.readFile (argv);
mysolver.findNcity ();
mysolver.giveGroupnum();
mysolver.solve();
return 0;
}
