作者:茶人2502933107 | 来源:互联网 | 2023-08-22 02:11
OkIhavetodoatopologicalsortingalgorithmonagraph.Ineedtofindthenodewithindegreeo
Ok I have to do a topological sorting algorithm on a graph. I need to find the node with in degree of 0 and queue it, then print it and remove all the edges going to it. I am removing the edges by decrementing the number of edges going into it in the countList map. I have the adjacency list as a map, and the count of in degrees for each node as a map. My algorithm is only accessing the first element of the adjacency list. so my output queue is only displaying the first key of the adjacency list map. over and over. I stopped the while loop at 25 so it wouldn't be infinite.
我需要在图上做一个拓扑排序算法。我需要找到具有0度的节点,并对其进行排队,然后打印并删除所有的边。我通过减少在countList映射中进入它的边的数量来去除这些边。我有邻接表作为映射,每个节点的度数作为映射。我的算法只访问邻接表的第一个元素。所以我的输出队列只显示了邻接表映射的第一个键。一遍又一遍。我在25处停止了while循环,这样它就不会是无限的。
string z = "";
string a = "";
cout <<"Queue: ";
do{
for(it = countList.begin(); it!=countList.end(); ++it){
if(it->secOnd== 0){
Q.push(it->first);
countList.at(it->first)--;
z = adjList[it->first];
cout <<"z: " <
Can someone help me with understanding why it is not iterating through the countList and is only staying on the first element?
有人能帮助我理解为什么它不能遍历countList并只停留在第一个元素上吗?
Thank you.
谢谢你!
So I changed the countList.at(a)-+1, to countList.at(a)-- for proper decrementation. Now the output is more than just the first vertex that was 0 in degree. But the output is still wrong.
所以我把countlist。at(a)-+1换成了countlist。at(a)来进行适当的递减。现在输出大于第一个度为0的顶点。但产出仍然是错误的。
Here is the whole thing. My variable declarations
这就是整个过程。我的变量声明
vector E;
map adjList;
mapcountList;
map::iterator it;
queue Q;
I don't want to put up the code for the adjacencyList or countList but here are how they look.
我不想为邻接列表或countList设置代码,但这里是它们的外观。
//These represent the edges between the two paired nodes
AdjacencyList: (1,2) (1,4) (1,3) (2,4) (2,5) (3,6) (4,6) (4,7) (4,3) (5,4) (5,7) (7,6)
//The first is the node name and the second element is how many edges come into that node.
countList: (1,0) (2,1) (3,2) (4,3) (5,1) (6,3) (7,2)
My output should be either:
我的输出应该是:
Queue: 1,2,5,4,3,7,6
//or
Queue: 1,2,5,4,7,3,6
OK I added
我补充道
countList.at(it->first)--;
countList.at(这- >第一);
after I push the vertex onto the queue. So that should decrement the count of that vertex to -1. This narrowed my output alot.
我把顶点推到队列上。所以这个顶点的计数应该减少到-1。这大大减少了我的产出。
OK IT WORKS NOW!!! I changed the while loop to stop after the queue is empty and printed the queue in the while loop and it fixed the problem.
现在它工作! ! !我将while循环更改为在队列为空后停止,并在while循环中打印队列,它修复了问题。
My output now is:
我现在的输出是:
Queue: 1, 2, 5, 4, 7, 3, 6,
Ok this code will only work if the node names are only single values. How would I change the adjList mapping for values that node names are longer than a single character? Perhaps a linked list being pointed to by the key value? And if so how would I do that?
好的,这段代码只在节点名只有一个值时才有效。对于节点名称长于单个字符的值,如何更改adjList映射?也许键值指向的链表?如果是的话,我该怎么做呢?
1 个解决方案