提升C++原始算法错误答案

Boost C++ prim algorithm wrong answer

本文关键字:错误 答案 算法 原始 C++ 提升      更新时间:2023-10-16

这个程序给了我最小生成树的权重和与起始节点的最远距离。但是在输入测试用例的数量以及顶点数和边数后,它需要两条边及其权重,并给出一些垃圾值。为什么?

#include<iostream>
#include<boost/config.hpp>
#include<boost/graph/adjacency_list.hpp>
#include<utility>
#include<boost/graph/prim_minimum_spanning_tree.hpp>
#include<vector>

using namespace std;
using namespace boost;
int main()
{
  typedef adjacency_list < vecS, vecS, undirectedS,property < vertex_distance_t, int>, property < edge_weight_t, int > > Graph;
  int no_test=0,v,e,m,a,b,c,w,d;
  cin>>no_test;
  int array_weights[100],array_distances[100],i,j;
  m=0;
  while(m!=no_test)
  {
    w=0;
    d=0;
    cin>>v>>e;//take input
    Graph g(v);//create graph g
    property_map < Graph,edge_weight_t > ::type weightMap;
    bool b;
    typedef graph_traits < Graph> ::edge_descriptor edge11;
    for(i=0;i<e;i++)  //add edges into g from i/p
    {
      edge11 ed;
      cin>>a>>b>>c;
      tie(ed, b)=add_edge(a, b, g);
      weightMap[ed]=c;
    }
    typedef graph_traits < Graph> ::vertex_descriptor vertex11;
    property_map<Graph,vertex_distance_t>::type distanceMap=get(vertex_distance,g);
    property_map<Graph,vertex_index_t>::type indexMap=get(vertex_index,g);
    vector < vertex11 > pred(v);
    prim_minimum_spanning_tree(g,*vertices(g).first,&pred[0],distanceMap,weightMap,indexMap,default_dijkstra_visitor());
    typedef graph_traits<Graph>::edge_iterator edge1;
    typedef graph_traits<Graph>::vertex_iterator vertex1;
    pair <edge1, edge1> edg;
    for(edg=edges(g);edg.first!=edg.second;++edg.first)
    {
      w=w+weightMap[*edg.first];
    }

    pair<vertex1,vertex1> vtx;
    for(vtx=vertices(g);vtx.first!=vtx.second;++vtx.first)
    {
      if(distanceMap[*vtx.first]>d)
      d=distanceMap[*vtx.first];
    }
    array_weights[m]=w;
    array_distances[m]=d;
    m++;
   }
  for(j=0;j<no_test;j++)
  {
    cout<<array_weights[j]<<" "<<array_distances[j]<<endl;
  }
return 0;
}

该程序编译 perfectly.it 给出两个以上边缘的问题。我只是不知道为什么。谢谢

程序的问题在于它声明了两个名为 b 的变量。一开始,程序声明一个名称为 b 的变量,类型为 int 。稍后它声明了一个名称为 b 的类型为 bool 的变量。第二个声明隐藏第一个声明。

当程序cin>>a>>b>>c;时,它将使用类型 boolb 。当你输入01以外的值时,b ,这将设置cin的故障位,因为该值不能解析为bool(引用)。在此之后,cin 将不会接受输入,直到调用 cin.clear(),这会重置故障位。由于您的程序不调用cin.clear(),它将不再接受输入并运行所有读取操作。

若要解决此问题,请将bool b;声明更改为bool inserted;,并将分配tie(ed, b) = add_edge(a, b, g);更改为 tie(ed, inserted) = add_edge(a, b, g);

此外,您可以在每次程序要求输入时添加进一步的错误检查。这可以通过检查每次输入后的cin.fail()结果来完成。如果没有这样的检查,如果用户输入无法解析为整数的无效值(例如某些字符串,例如abc),也会出现问题。

作为旁注,我建议使用增加的编译器警告进行编译。这可以帮助您检测上述问题。例如,使用 g++clang++ 编译程序时,使用标志-Wall启用警告将导致有关第一个b未使用的警告。