从team.txt中读取参赛队伍的基本信息,实现基于二叉排序树的查找。根据提示输入参赛队编号,若查找成功,输出该赛事类别对应的基本信息(参赛作品名称、参赛学校、赛事类别、参赛者和指导老师信息),同时,输出查找成功时的平均查找长度ASL;否则,输出“查找失败!”。
时间: 2024-02-19 08:02:34 浏览: 94
好的,以下是一个从 `team.txt` 文件中读取参赛队伍的基本信息,实现基于二叉排序树的查找的 C++ 程序。程序会提示用户输入参赛队编号,如果查找成功,会输出该赛事类别对应的基本信息,同时输出查找成功时的平均查找长度 ASL。如果查找失败,会输出“查找失败!”。
```
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct TeamInfo {
int id;
string name;
string school;
string type;
string players;
string teacher;
};
struct TreeNode {
TeamInfo team;
TreeNode *left;
TreeNode *right;
};
class BinarySearchTree {
private:
TreeNode *root;
public:
BinarySearchTree() {
root = NULL;
}
void insertNode(TeamInfo team) {
TreeNode *newNode = new TreeNode;
newNode->team = team;
newNode->left = NULL;
newNode->right = NULL;
if (root == NULL) {
root = newNode;
}
else {
TreeNode *current = root;
TreeNode *parent = NULL;
while (true) {
parent = current;
if (team.id < current->team.id) {
current = current->left;
if (current == NULL) {
parent->left = newNode;
break;
}
}
else {
current = current->right;
if (current == NULL) {
parent->right = newNode;
break;
}
}
}
}
}
TreeNode* searchNode(int id, int &asl) {
if (root == NULL) {
return NULL;
}
else {
TreeNode *current = root;
asl = 1;
while (current->team.id != id) {
if (id < current->team.id) {
current = current->left;
}
else {
current = current->right;
}
asl++;
if (current == NULL) {
return NULL;
}
}
return current;
}
}
};
int main() {
ifstream fin("team.txt");
BinarySearchTree bst;
string line;
while (getline(fin, line)) {
TeamInfo team;
sscanf(line.c_str(), "%d %s %s %s %s %s", &team.id, &team.name[0], &team.school[0], &team.type[0], &team.players[0], &team.teacher[0]);
bst.insertNode(team);
}
fin.close();
int id;
cout << "请输入参赛队编号:";
cin >> id;
int asl;
TreeNode *result = bst.searchNode(id, asl);
if (result == NULL) {
cout << "查找失败!" << endl;
}
else {
cout << "参赛作品名称:" << result->team.name << endl;
cout << "参赛学校:" << result->team.school << endl;
cout << "赛事类别:" << result->team.type << endl;
cout << "参赛者:" << result->team.players << endl;
cout << "指导老师:" << result->team.teacher << endl;
cout << "平均查找长度 ASL:" << asl << endl;
}
return 0;
}
```
在上面的代码中,我们定义了 `TeamInfo` 结构体来存储参赛队伍的基本信息,定义了 `TreeNode` 结构体作为二叉排序树的节点,以及定义了 `BinarySearchTree` 类来实现二叉排序树的相关操作。在 `main` 函数中,我们首先从 `team.txt` 文件中读取参赛队伍的基本信息,并将其插入二叉排序树中。然后,程序会提示用户输入参赛队编号,通过调用 `searchNode` 方法在二叉排序树中查找对应的节点。如果查找成功,会输出该赛事类别对应的基本信息,同时输出查找成功时的平均查找长度 ASL;否则,会输出“查找失败!”。
阅读全文