我很难解决一个问题,这个问题要求我用4个随机数a,b,c,d生成一个边图,所以公式如下,要生成图的节点,我们使用变量d,如果我们用3除以d,得到剩余的0,然后生成10个节点,如果d/3 =1,那么11点,如果d/3 =2,则生成12个节点,对于边,我们有下面的公式(i,j)∈U <-> ((ai+bj)/c) /d≤1,基本上,如果除以d后的公式给出一个较小或等于1的余数,则边将i和j的边沿连接起来。有人能告诉我下面的代码有什么问题吗?
以下是代码:
#include <iostream>
#include <vector>
using namespace std;
struct Edge {
int src, dest;
};
class Graph
{
public:
vector<vector<int>> adjList;
Graph(vector<Edge> const& edges, int N)
{
adjList.resize(N);
for (auto& edge : edges)
{
adjList[edge.src].push_back(edge.dest);
}
}
};
void printGraph(Graph const& graph, int N)
{
for (int i = 0; i < N; i++)
{
cout << i << " ——> ";
for (int v : graph.adjList[i])
{
cout << v << " ";
}
cout << endl;
}
}
int main()
{
vector<Edge> edges;
int a, b, c, d,remainder,Nodges,result;
cout << "Enter 4 values : \n";
cin >> a >> b >> c >> d;
remainder = d % 3;
if (remainder == 0)
{
Nodges = 10;
}
else if (remainder == 1)
{
Nodges = 11;
}
else if (remainder == 2)
{
Nodges = 12;
}
for (int i = 0; i < Nodges; i++)
{
for (int j = 0; j < Nodges; j++)
{
result = ((a * i + b * j) / c) % d;
if (result <= 1)
{
edges =
{
{i,j}
};
}
}
}
Graph graph(edges, Nodges);
printGraph(graph, Nodges);
return 0;
}发布于 2021-05-25 06:41:20
首先,您不处理d超出所需范围的情况。如果d是37,那么您就没有初始化Nodges,然后通过读取它来调用未定义的行为。您可以添加一个最后的else来捕捉这种情况,为空图或消息打印一些表示,然后返回,这样就根本不满足for循环了。
不过,更简单:
if(remainder < 3)
{
nodes = 10 + remainder;
// your for loops here
}如果您无论如何都想创建一个空图,那么不要忘记将nodes初始化为0;否则,您也应该在上面的if块中包含图形代码。
但是,您的代码失败的要点是:
edges =
{
{i,j}
};通过这种方式,您可以一次又一次地创建一个新向量,总是包含一个元素,而旧的一个被替换。
你真的需要:
edges.emplace_back(i, j);最后:习惯于在输入操作后始终检查流的状态。用户倾向于提供无效的输入,如果您没有捕捉到您可能会得到意想不到的、实际上是未定义的行为(例如,除以0)。
if(std::cin >> a >> b >> c >> d)
{
/* your code */
}
else
{
// handle invalid input, e. g. by printing some message
// if you want to go on reading the stream:
// clears the error flags:
std::cin.clear();
// clears the stream's buffer yet containing the invalid input:
std::cin.ignore(numeric_limits<streamsize>::max(), '\n');
}https://stackoverflow.com/questions/67628126
复制相似问题