题目链接 : https://nanti.jisuanke.com/t/36115
字典树裸题
#include<bits/stdc++.h>
using namespace std;
string str[100005];
typedef struct node
{
int num;
node *rt[26];
node()
{
num = 0;//初始化
for(int i = 0; i < 26; i++)
rt[i] = NULL;
}
}NODE;
NODE *tree;
void insert(NODE *tree, int num)
{//cout << "eeee" << endl;
int i;
int lena = str[num].length();//记下长度
for(i = lena-1; i >= 0; i--)
{
if(tree->rt[str[num][i] - 'a'] == NULL)//等于NULL 新建节点
tree->rt[str[num][i] - 'a'] = new NODE();
tree = tree->rt[str[num][i] - 'a'];//往后走
tree->num++;//计数
}
}
int query(NODE *tree, int num)
{//cout << "qqq" << endl;
int i;
int lena = str[num].length();
for(i = lena-1; i >=0; i--)
{
tree = tree->rt[str[num][i] - 'a'];//往后走
if(tree == NULL) return 0;//等于NULL 没有此前缀
}
return tree->num;//返回值
}
int main()
{
int i;
tree = new NODE();
int n;
while(cin >> n)
{
for(i = 0; i < n; i++)
{
cin >> str[i];
insert(tree, i);
}
for(i = 0; i < n; i++)
{
int temp = query(tree, i);
printf("%d\n", temp);
}
}
}