ZBLOG

根据类的声明 template class ALDirNetwork { protected: int vexNum, vexMaxSize, arcNum; //实际顶点数目,顶点数组容量和实际弧数 WeightType infinity; //存储表示无穷大的值 ALNetworkVex *vexs; //指向顶点数组的指针 int*ve...

以下是完善后的深搜代码:

void Pathofwealth(ALDirNetwork<char, int>& graph, int* &path, int* &ans, int index, int final, int& danger, int& wealth, int& maxwealth)
{
    if (danger >= 100) return;
    else if (index == final)
    {
        if (wealth > maxwealth)
        {
            for (int i = 0; i < graph.GetVexNum(); i++)
            {
                ans[i] = path[i];
            }
            maxwealth = wealth;
        }
        return;
    }

    // 获取当前顶点的邻接点
    int adjvex = graph.GetFirstAdjvex(index);
    while (adjvex != -1)
    {
        // 如果邻接点未被访问,则继续递归遍历
        if (graph.GetVisitedTag(adjvex) == UNVISITED)
        {
            // 更新危险值和财富值
            WeightType weight = graph.GetWeight(index, adjvex);
            danger += weight;
            wealth += graph.GetWealth(adjvex);

            // 设置访问标志并更新路径
            graph.SetVisitedTag(adjvex, VISITED);
            path[index + 1] = adjvex;

            // 继续递归遍历下一个顶点
            Pathofwealth(graph, path, ans, index + 1, final, danger, wealth, maxwealth);

            // 回溯时恢复状态
            danger -= weight;
            wealth -= graph.GetWealth(adjvex);
            
            graph.SetVisitedTag(adjvex, UNVISITED);
        }
        
        adjvex = graph.GetNextAdjvex(index, adjvex);
    }
}

void MaxWealthOfPath(ALDirNetwork<char, int>& graph)
{
    int final = graph.GetVexNum() - 1;
    int* path = new int[graph.GetVexNum()];
    int* ans = new int[graph.GetVexNum()];
    memset(path, -1, sizeof(int) * graph.GetVexNum());
    memset(ans, -1, sizeof(int) * graph.GetVexNum());
    
    int danger = 0, wealth = 0, maxwealth = 0;
    
    // 标记起点为已访问
    graph.SetVisitedTag(0, VISITED);
    path[0] = 0;

    Pathofwealth(graph, path, ans, 0, final, danger, wealth, maxwealth);

    cout << "The Max Wealth of Path is:" << endl;
    
    int i = 0;
    while (ans[i] != -1)
    {
        char ch;
        graph.GetElem(ans[i], ch);
        cout << ch << "  ";
        i++;
    }
    
    delete[] path;
    delete[] ans;
}

以上代码在给定的有向网中找出最大财富值的路径,并输出该路径。函数 MaxWealthOfPath 使用深度优先搜索(DFS)来遍历所有可能的路径,并更新最大财富值和对应的路径。

请注意,在使用此代码之前,请确保 ALDirNetwork 类中相关方法的实现是正确的,特别是获取顶点价值的方法 GetWealth、设置顶点访问标志的方法 SetVisitedTag、获取第一个邻接点和下一个邻接点的方法 GetFirstAdjvexGetNextAdjvex


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?