ZBLOG

根据Getwealth代码, template Status ALDirNetwork::GetWealth(int v, int& e) const { //获取顶点v的数据元素值 if (v < 0 || v >= vexNum) //判断v是否越界 { cout

根据您提供的代码,我将替换GetWealth函数并修改MaxWealthPathOutputMaxWealthPath函数。请查看下面的修改后代码:

template<class DataType, class WeightType>
Status ALDirNetwork<DataType, WeightType>::GetWealth(int v, int& e) const {    // 获取顶点v的财富值
    if (v < 0 || v >= vexNum) {                        // 判断v是否越界
        cout << "v取值不合法!" << endl;  return FAILED;
    }
    e = vexsW[v];
    return SUCCESS;
}

void MaxWealthPath(ALDirNetwork<char, int>& graph, int v0, int*& dist, int* path)
{
    int infinity = graph.GetInfinity();
    int v, u;

    for (v = 0; v < graph.GetVexNum(); v++) { // 初始化dist数组和path数组
        dist[v] = -infinity; // 初始化为负无穷大
        path[v] = -1; // 初始化路径为-1
        graph.SetVisitedTag(v, UNVISITED);
    }

    dist[v0] = 0; // 起点的财富值设置为0

    for (int i = 1; i < graph.GetVexNum(); i++)
    {
        u = -1;
        
        for (v = 0; v < graph.GetVexNum(); v++)
        {
            if (graph.GetVisitedTag(v) == UNVISITED && (u == -1 || dist[v] > dist[u]))
            {
                u = v;
            }
        }

        if (u == -1) {
            break; // 如果u仍然为-1,说明剩下的顶点都无法到达,跳出循环
        }

        graph.SetVisitedTag(u, VISITED);

        for (v = graph.GetFirstAdjvex(u); v != -1; v = graph.GetNextAdjvex(u, v))
        {
            WeightType weight;
            graph.GetWeight(u, v, weight);

            if (graph.GetVisitedTag(v) == UNVISITED && dist[u] + weight > dist[v])
            {
                dist[v] = dist[u] + weight;
                path[v] = u;
            }
        }
    }
}

void OutputMaxWealthPath(ALDirNetwork<char, int>& graph, int v, int*& dist, int* path)
{
    char vertex;
    graph.GetElem(v, vertex);

    int i = graph.GetVexNum() - 1;

    if (i != v) {
        char destVertex;
        graph.GetElem(i, destVertex);

        cout << endl;
        cout << "The Max Wealth of the path between " << vertex << " and " << destVertex << " is: ";

        // 输出路径
        SqStack<int> stack;
        int index = i;

        while (path[index] != -1) {
            stack.Push(index);
            index = path[index];
        }

        std::cout << vertex;

        while (!stack.IsEmpty()) {
            char tmp;
            int k;
            stack.Pop(k);
            graph.GetElem(k, tmp);
            cout << " -> " << tmp;
        }

        cout << endl;
		cout << "The Wealth is: " <<  dist[i] << endl;
    }
}

希望这能对您有所帮助!如果还有其他问题,请随时提问。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?