帮我让此代码输出查找的单词
时间: 2024-03-20 16:41:12 浏览: 15
要让代码输出查找的单词,只需要在`Search`函数中记录下查找的单词即可。具体实现上,可以使用一个字符串变量`word`来记录当前查找的单词,每次遍历到一个字符,就将该字符添加到`word`中。当遍历完整个单词后,就可以返回该单词在字典树中的出现次数,并将`word`输出。
修改后的代码如下:
```cpp
using namespace std;
int sum[1000010]={0};
int tree[1000010][26];
int cnt=0;
void Insert(char s[]) {
int root=0;
for(int i=0;s[i];i++) {
int id=s[i]-'a';
if(tree[root][id]==0) tree[root][id]=++cnt;
sum[tree[root][id]]++;
root=tree[root][id];
}
}
int Search(char s[]) {
int root=0;
string word = ""; // 记录查找的单词
for(int i=0;s[i];i++) {
int id=s[i]-'a';
if(tree[root][id]==0) return 0;
root=tree[root][id];
word += s[i]; // 将当前字符添加到word中
}
cout << "Search word: " << word << endl; // 输出查找的单词
return sum[root];
}
int main() {
char s[20];
while(gets(s)) {
if(s[0]==NULL) break;
Insert(s);
}
while(gets(s)) {
cout << Search(s) << endl;
}
return 0;
}
```
运行后,每次输出出现次数时,都会额外输出一行表示查找的单词。