ZBLOG

在此基础上给出路径的各节点

在上述示例代码中,我们可以根据关键路径算法的逻辑,添加一些额外的代码来输出关键路径上的各个节点。

  1. void findCriticalPath() {
  2. vector<int> inDegree(numVertices, 0);
  3. for (int u = 0; u < numVertices; ++u) {
  4. for (auto& edge : adjacencyList[u]) {
  5. int v = edge.first;
  6. ++inDegree[v];
  7. }
  8. }
  9. vector<int> startTime(numVertices, 0);
  10. vector<int> endTime(numVertices, 0);
  11. queue<int> q;
  12. for (int u = 0; u < numVertices; ++u) {
  13. if (inDegree[u] == 0) {
  14. q.push(u);
  15. }
  16. }
  17. while (!q.empty()) {
  18. int u = q.front();
  19. q.pop();
  20. for (auto& edge : adjacencyList[u]) {
  21. int v = edge.first;
  22. int weight = edge.second;
  23. inDegree[v]--;
  24. startTime[v] = max(startTime[v], startTime[u] + weight);
  25. if (inDegree[v] == 0) {
  26. q.push(v);
  27. }
  28. }
  29. endTime[u] = startTime[u];
  30. }
  31. int criticalPathLength = *max_element(endTime.begin(), endTime.end());
  32. cout << "Critical path length: " << criticalPathLength << endl;
  33. // 输出关键路径上的节点
  34. cout << "Critical path nodes: ";
  35. int currentNode = -1;
  36. for (int i = 0; i < numVertices; ++i) {
  37. if (endTime[i] == criticalPathLength && currentNode == -1) {
  38. currentNode = i;
  39. cout << currentNode << " ";
  40. } else if (endTime[i] == criticalPathLength && startTime[i] == startTime[currentNode]) {
  41. currentNode = i;
  42. cout << currentNode << " ";
  43. }
  44. }
  45. cout << endl;
  46. }

findCriticalPath()函数中,我们增加了一段代码来输出关键路径上的各个节点。这里使用了一个currentNode变量来跟踪当前节点,并根据结束时间和开始时间进行判断,找到关键路径上的节点并输出。

这样,在调用graph.findCriticalPath()之后,除了输出关键路径长度外,还会输出关键路径上的各个节点。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=16069

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?