ZBLOG

使用图(Graph)数据结构:可以将每个球队看作图的一个节点,并建立比赛结果之间的有向边。通过图的深度优先搜索(DFS)或广度优先搜索(BFS)算法,实现改代码的相同功能:#include #include #include #include using namespace std; //定义二叉树结点 struct BTNode { string data; BTNode* lc; BTNod...

以下是使用图数据结构进行深度优先搜索(DFS)的代码实现:

#include <iostream>
#include <map>
#include <queue>
#include <string>

using namespace std;

// 定义图节点
struct GraphNode {
    string team;
    vector<GraphNode*> neighbors;

    GraphNode(string name) : team(name) {}
};

// 创建图
GraphNode* createGraph(map<string, int>& gamesum, map<string, string>& loserteam) {
    string teamname;
    queue<GraphNode*> nodes;

    cin >> teamname;
    // 创建根节点
    GraphNode* root = new GraphNode(teamname);
    nodes.push(root);

    while (cin >> teamname && teamname != "#") {
        GraphNode* current = nodes.front();
        nodes.pop();
        
        // 创建左子节点
        if (teamname != "#") {
            GraphNode* leftChild = new GraphNode(teamname);
            current->neighbors.push_back(leftChild);
            nodes.push(leftChild);

            // 更新比赛次数和败者信息
            gamesum[teamname]++;
            if (current->team != teamname)
                loserteam[teamname] = current->team;
        }

        // 创建右子节点
        cin >> teamname;
        if (teamname != "#") {
            GraphNode* rightChild = new GraphNode(teamname);
            current->neighbors.push_back(rightChild);
            nodes.push(rightChild);

            // 更新比赛次数和败者信息
            gamesum[teamname]++;
            if (current->team != teamname)
                loserteam[teamname] = current->team;
        }
    }

    return root;
}

void dfs(GraphNode* node, map<string, int>& gamesum, map<string, string>& loserteam) {
    if (node == nullptr)
        return;

    for (GraphNode* neighbor : node->neighbors) {
        // 更新比赛次数和败者信息
        gamesum[neighbor->team]++;
        if (node->team != neighbor->team)
            loserteam[neighbor->team] = node->team;
        
        dfs(neighbor, gamesum, loserteam);
    }
}

int main() {
    map<string, int> gamesum; // 比赛次数
    map<string, string> loserteam; // 败者信息

    GraphNode* root = createGraph(gamesum, loserteam);

    int t; // 查询次数
    cin >> t;
    while (t--) {
        string team;
        cin >> team;

        if (gamesum.find(team) == gamesum.end())
            cout << "Not Found" << endl;
        else if (team == root->team)
            cout << gamesum[team] << " Champion!" << endl;
        else
            cout << gamesum[team] << " " << loserteam[team] << endl;
    }

    return 0;
}

使用图数据结构可以更直观地表示比赛结果之间的关系,并通过深度优先搜索遍历图中的节点,更新比赛次数和败者信息。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?