以下是使用图数据结构进行深度优先搜索(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助手提供,问题来源于学员提问