gpt4 book ai didi

c++ - 创建具有正确边的无向图

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:15:18 26 4
gpt4 key购买 nike

您好,我正在创建 100 个图表用于在 dijkstra 算法中进行测试。我检查以确保连接的两个随机生成的节点号不相同。但是我不明白如何检查一对是否已经存在,以便两个节点之间出现多个边缘。如何防止两个节点之间出现两条边?

void mapDataGenerator(int start, int end, int iterations,
int *pathCount, int *weightCount, int *timeCount)
{
int nodeCount = rand() % 8128 + 64;
edgeListTemplate edgeList(nodeCount);
//cout << "The node count is: " << nodeCount;
int n = 0;
list<vertex_v> path;
vector<weight_w> min_distance;
vector<vertex_v> previous;


while (n != nodeCount)
{

int nodeNumb = (rand() % nodeCount); // Generates a possible node 1
int nodeDest = (rand() % nodeCount); // Generates a possible node 2

//cout << "The node connection 1 is: " << nodeNumb << endl;
//cout << "The node connection 2 is: " << nodeDest << endl;
int node_weight = rand() % 5 + 1; // Generate random weight of node

//cout << "The node weight is: " << node_weight << endl;

// Create adjacency list
if (nodeNumb != nodeDest) // if the random nodes generated are not same
{
edgeList[nodeNumb].push_back(node(nodeDest, node_weight));
// For undirected graph create opposite connection back
edgeList[nodeDest].push_back(node(nodeNumb, node_weight));
++n;
}
}

最佳答案

您可以简单地使用映射/集合数据结构来跟踪已经存在的边。精确映射对将完成这项工作。

代码

// map declaration
map<pair<int, int>, bool> M;

if (nodeNumb != nodeDest && !M.count(make_pair(nodeNumb, nodeDest))) // if the random nodes generated are not same
{
// Marking the pair of edges
M[make_pair(nodeNumb, nodeDest)] = true;
edgeList[nodeNumb].push_back(node(nodeDest, node_weight));
// For undirected graph create opposite connection back
edgeList[nodeDest].push_back(node(nodeNumb, node_weight));
++n;
}

关于c++ - 创建具有正确边的无向图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34389048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com