在来这里之前我已经很努力地做了我的研究。下面的代码崩溃了,我怀疑cout的滥用。(这不应该是最优化的实现,但暂时还不是 pb)
有经验的人能看出问题出在哪里吗?
提前谢谢了
#include <cmath>
#include <iostream>
#include <cstdlib>
#include <fstream> //file io
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;
template <typename T>
string NumberToString ( T Number )
{
ostringstream ss;
ss << Number;
return ss.str();
}
class Point { //an instance of this class represents the integer triples: (i, j, cost).
int Edge1, Edge2, Cost;
public:
Point(int x, int y, int z) : Edge1(x), Edge2(y), Cost(z) {}
Point() {Edge1=Edge2=Cost=0;}
bool operator<(Point const &other) {
return (Cost < other.Cost);
}
void setEdge1(int x){this->Edge1=x;}
void setEdge2(int x){this->Edge2=x;}
void setCost(int x){this->Cost=x;}
int getEdge1(){return this->Edge1;}
int getEdge2(){return this->Edge2;}
int getCost(){return this->Cost;}
};
class GRAPH
{
private:
vector<Point> GraphMatrix;
int GRAPH_vertex=0;
int initialised=0;
public:
GRAPH(string Path)
{
this->initialised=1;
// import input data from file
vector<int> reader(10);
ifstream ifp(Path, ios::in);
int ii = 0;
while(!ifp.eof() )
{
ifp >> reader[ii++];
if (ii%9 ==0)
reader.resize(reader.size() +10);
}
reader.resize(ii-1);
//End of data import
this->GRAPH_vertex=reader[0];// Number of vertices set
for(int i=0;i<(ii-2)/3;i++)
{
Point punto(reader[1+3*i],reader[2+3*i],reader[3+3*i]);
GraphMatrix.insert(GraphMatrix.end(),punto);
}
}
//Copy constructor omited
~GRAPH() //destructor
{
if (this != NULL)
delete this;
}
int Get_GRAPH_vertex(){return GRAPH_vertex;}
vector<Point> Get_GraphMatrix() {return GraphMatrix;}
void Kruskal();
friend bool compareTwoPoint(Point,Point);
};
bool compareTwoPoint(Point rowA, Point rowB){
return ( rowA.getCost()<rowB.getCost() );
}
void GRAPH::Kruskal()
{
int n_vertices=this->GRAPH_vertex;
std::sort(GraphMatrix.begin(),GraphMatrix.end(),&compareTwoPoint);
vector <int> temp1(n_vertices*n_vertices,0);
int minimumcost=0;
int Iteration=0;
vector<string> Tree;
for (std::vector<Point>::iterator it=GraphMatrix.begin(); it!=GraphMatrix.end(); ++it)
{
int ii=it->getEdge1();
int jj=it->getEdge2();
if((temp1[ii+n_vertices*jj] !=1)&& Iteration<n_vertices)
{
temp1[ii+n_vertices*jj]=1;
temp1[jj+n_vertices*ii]=1;
minimumcost+=it->getCost();
Iteration+=1;
Tree.push_back(NumberToString(ii)+"->"+ NumberToString(jj));
}
}
cout<<Iteration<<'\n';
cout<<"minimum cost is"+ NumberToString(minimumcost)<<'\n';
for (vector<string>::iterator p = Tree.begin();
p != Tree.end(); ++p)
{
cout << *p << '\n';
cout << endl;
}
}
int main()
{
GRAPH grafe("C:/Users/Algoris/Desktop/simplon.txt");
grafe.Kruskal();
}
//txt文件输入示例
20
0 1 17
0 2 2
0 3 9
0 4 24
0 5 28
0 6 29
0 7 14
0 8 28
0 9 13
0 10 23
0 11 10
0 12 15
0 13 23
0 14 15
0 15 18
0 16 11
0 17 4
0 18 27
0 19 5