C++点坐标创建图形并查找 MST

C++ creating a graph out of dot coordinates and finding MST

本文关键字:查找 MST 图形 创建 坐标 C++      更新时间:2023-10-16

我正在尝试制作一个程序,其中用户输入n点坐标,0 <= 100。假设,这些点必须连接起来,比如说,用墨水连接,例如,你可以沿着墨水线并使用尽可能少的墨水从A点到X点。

我想过使用 Prim 算法或类似的东西来获取 MST,但为此我需要一个图表。在我看过的所有网页中,他们并没有真正解释这一点,他们总是已经有边缘的图表。

我需要帮助,专门从一堆 (x, y( 坐标中C++创建一个图表,例如用户输入:

    0
  • 0
  • 4
  • 4
  • 4 0
  • 0 4

请注意,我只是从C++开始,我不能使用任何奇怪的库,因为这适用于像 CodeForce 这样的页面,您只能使用本机库。

(对于那些也在这样做并在这里寻求帮助的人,此输入的正确输出将是 12(

假设一个完整的图表可能是最合适的,如"Beta"所建议的那样。

下面的代码可能会在数组点列表中的每对两个点之间创建边,并返回创建的边数。执行此代码后,您可以应用原始算法来查找 MST。

// Definition of Structure "node" and an array to store inputs
typedef struct node {
        int x; // x-cordinate of dot
        int y; // y-cordinate of dot
} dots[100]; 
// Definition of Structure "edge"
typedef struct edge {
         int t1; // index of dot in dots[] for an end.
         int t2; // index of dot in dots[] for another end.
         float weight; // weight (geometric distance between two ends) 
} lines[];
// Function to create edges of complete graph from an array of nodes.
//   Argument: number of nodes stored in the array dots.
//   ReturnValue: number of edges created.
//   Assumption: the array lines is large enough to store all edges of complete graph
int createCompleteGraph(int numberOfNodes){
  int i,j,k,x-diff,y-diff;
  k=0; // k is index of array lines
  for (i=0; i<numberOfNodes-1; i++) {// index of a node at one end
    for (j=i+1; j<numberOfNodes; j++) {// index of a node at another end
      lines[k].t1 = i;
      lines[k].t2 = j;
      x-diff = dots[i].x - dots[j].x;
      y-diff = dots[i].y - dots[j].y;
      lines[k].weight = sqrt(x-diff * x-diff + y-diff * y-diff) // calculate geometric distance
      k++; 
    }
  }
  return k;
}