Хорошо, ребята, я не видел этого нигде в Интернете, и я пытался понять это в течение нескольких дней. Как я могу найти MST набора координат из входного файла, используя алгоритм Прима. Есть несколько вещей о том, как это сделать, но если следовать им и быть новичком в C++, они не очень помогут. Может ли кто-нибудь показать мне КОД (желательно) о том, как решить эту проблему?
Предположим, у меня есть набор координат во входном файле "Something.txt", содержащий:
(N количество узлов/вершин)
(x Coord), (y coord)
и т.д...
Eg:
9
50 100
100 150
200 150
300 150
350 100
300 50
200 50
100 50
150 100
Учитывая, что эти точки уже нанесены на график, как будет написан алгоритм Прима? Я понимаю, что это много, но сейчас я совершенно не понимаю, как новичок в C++. (и да, я пытался вырезать код, я пытался смотреть на другие примеры и крутить их, чтобы заставить его работать, я пробовал почти все, кроме того, что видел, как это делается, чтобы я мог лучше понять, что я продолжай отсутствовать.)
Заранее спасибо.
Редактировать: код, отображающий точки через pygraphics, используя входной файл аргумента .txt, который вы передаете ему, который затем переходит в файл .dat, который затем публикуется через предварительно созданный файл построения:
class Point
{
public:
// Constructor.
Point()
{
x = 0; y = 0;
} // end constructor
Point(int a, int b, int id)
{
x = a; y = b; pointID = id;
} // end constructor
int getX() { return x; }
int getY() { return y; }
int getID() { return pointID; }
string data;
Point(string x)
{
data = x;
}
private:
int x = 0;
int y = 0;
int v;
int xVert;
int yVert;
int pointID = 0;
list<Point*> pointList;
list<Point*> neighbors;
//vector<Neighbor> myNeighborvector;
//locate point containg value x
Point * findPoint(string x)
{
for(Point * v : pointList)
{
if (v->data == x)
return v;
}
return NULL;
}
//add Neighbor going from x to y
void addDirectedNeighbor(string x, string y)
{
Point * xVert = findPoint(x);
Point * yVert = findPoint(y);
xVert->neighbors.push_back(yVert); //I would think that this should only add y to x's neighbors, but when I try to display I get x as one of y's neighbors
}
void addNeighbor(string x, string y)
{
addDirectedNeighbor(x, y);
addDirectedNeighbor(y, x);
}
}; // end class Point
//--------------------------------------------------------------------------
class Edge
{
public:
// Constructor.
Edge()
{
} // end constructor
Edge(Point ptA, Point ptB)
{
pointA = ptA;
pointB = ptB;
length = sqrt(pow(abs(pointA.getX() - pointB.getX() ), 2) + pow(abs(pointA.getY() - pointB.getY() ), 2) );
} // end constructor
Point getPtA() { return pointA; }
Point getPtB() { return pointB; }
double getLen() { return length; }
int getPtAID() { return pointA.getID(); }
int getPtBID() { return pointB.getID(); }
private:
Point pointA;
Point pointB;
double length;
}; // end class Edge
//--------------------------------------------------------------------------
/*class Neighbor
{
public:
// Constructor.
Neighbor()
{
length = sqrt(pow(abs(pointA.getX() - pointB.getX() ), 2) + pow(abs(pointA.getY() - pointB.getY() ), 2) );
} // end constructor
double getLen() { return length; }
private:
double length;
int pointID = 0;
};*/ // end class Neighbor
vector<Point> myPointvector; // vector will expand as needed
vector<Edge> MinSpanTree;
int main (int argc, char *argv[])
{
ifstream fin;
int coordPairs; // number of coordinate pairs in the file
int ptX, ptY;
int loopCounter;
int pointCounter = 0;
double MSTLength = 0.0;
// Check the number of arguments. Expected: filename of a file
if (argc != 2) // This check is often hardcoded
{ // If failure in parameters, offer advice for correction
cout << "\nThis program uses command-line argument.\n";
cout << "Usage: a.exe <filename>\n";
exit(0);
}
try // All lines within this block are part of the same exception handler
{
fin.open(argv[1]);
}
catch (exception& ex)
{
cout << ex.what(); // display standard explanation of the exception
exit(0); // exit the program
}
// Read from the file, one token at a time. If the type of token is known, it
// can be read into a corresponding variable type, such as
// in >> x; // Read the first item into an integer variable x.
// in >> str; // Read the next item into a string variable str.
// This line provides the graphic window setup.
cout << "800 600 white" << endl;
fin >> coordPairs;
cout << coordPairs << endl;
while (fin >> ptX)
{
// Do something with the element read from the file
// cout << ptX << endl;
fin >> ptY;
// cout << ptY << endl;
cout << "circle " << ptX << " " << ptY << " " << 20 << " seagreen" << endl;
Point dummyPoint(ptX, ptY, pointCounter++);
myPointvector.push_back(dummyPoint); // vector will expand as needed
cout << "Now myPointvector has size " << myPointvector.size() << endl;
} // end while
fin.close();
return 0;
}
Vertex
, каждый из которых содержит две координаты (x,y) и набор соседи (каждый из которых состоит из идентификационного номера и расстояния). Набор вещей может храниться в контейнере, таком как массив илиstd::vector
. - person Beta   schedule 04.02.2016x
,y
и идентификационный номер. И функция, которая берет две вершины и возвращает расстояние между ними. Кроме того, немного поиграйте сstd::vector
, добавляя элементы, удаляя элементы, перебирая вектор. - person Beta   schedule 04.02.2016Vertex
и вы освоите основыstd::vector
, мы можем работать над построением деревьев. Или, если вы хотите, чтобы я написал все для вас, я беру 100 долларов в час. - person Beta   schedule 04.02.2016