提升C++原始算法错误答案
Boost C++ prim algorithm wrong answer
这个程序给了我最小生成树的权重和与起始节点的最远距离。但是在输入测试用例的数量以及顶点数和边数后,它需要两条边及其权重,并给出一些垃圾值。为什么?
#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;
时,它将使用类型 bool
的b
。当你输入0
或1
以外的值时,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
未使用的警告。
相关文章:
- 递归求和任务的错误答案
- 为什么我在代码厨师的 CMPRSS 问题中得到 WA(错误答案)?
- 请找出我的代码中的错误,它在提交得到错误答案的同时仍然适用于我的所有测试用例
- 寻找最小楼梯成本的动态规划问题的错误答案
- 为什么可变大小的数组会导致Codechef出现错误答案
- 如何修复此代码对几个测试用例的错误答案?
- 使用幂函数的计算给出了大数字的错误答案
- 快速排序算法,一些特定输入序列的错误答案和分段错误
- 二分法程序的错误答案(C++)
- 无法理解绘图程序中的错误答案
- C++ - 整数除以整数返回错误答案
- 布尔函数的错误答案
- SPOJ FASTFLOW上的错误答案
- 代码的错误答案是在Java Camel案件和C 下划线标识符之间转换的错误答案
- 200万以下所有素数的总和,线程给出错误答案
- 0-1整数背包返回错误答案(动态编程)
- UVa 在线判断 - 3n + 1 - 错误答案
- 提升C++原始算法错误答案
- 二项式系数函数C++错误答案 n>13
- 需要帮助以避免 SPOJ 上的"错误答案"