要求:前缀树,输入前缀求和,每个字符串有个int映射
思路:最简单当然是搞个map[string]=int了,这里用字典树,isend用映射int代替了不为0表示结尾,求和时简单遍历前缀,队列层序,注意本题有的字符串是别的字符串的前缀
class MapSum {
private:
int val;
MapSum* next[26];
public:
MapSum() {
val=0;
memset(next,0,sizeof(next));
}
void insert(string key, int val) {
MapSum* cur=this;
for(char c:key){
if(cur->next[c-'a']==nullptr)
cur->next[c-'a']=new MapSum;
cur=cur->next[c-'a'];
}
cur->val=val;
}
int sum(string prefix) {
MapSum* cur=this;
for(char c:prefix){
if(cur->next[c-'a']==nullptr)return 0;//都没有求毛线
cur=cur->next[c-'a'];
}
queue<MapSum*> q;
int sum=0;
q.push(cur);
while(!q.empty()){
cur=q.front();
sum+=cur->val;
q.pop();
for(MapSum* n:cur->next)
if(n)q.push(n);
}
return sum;
}
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum* obj = new MapSum();
* obj->insert(key,val);
* int param_2 = obj->sum(prefix);
*/
dfs优化一下空间
class MapSum {
private:
int val;
MapSum* next[26];
public:
MapSum() {
val=0;
memset(next,0,sizeof(next));
}
void insert(string key, int val) {
MapSum* cur=this;
for(char c:key){
if(cur->next[c-'a']==nullptr)
cur->next[c-'a']=new MapSum;
cur=cur->next[c-'a'];
}
cur->val=val;
}
int sum(string prefix) {
MapSum* cur=this;
for(char c:prefix){
if(cur->next[c-'a']==nullptr)return 0;//都没有求毛线
cur=cur->next[c-'a'];
}
int sum=0;
dfs(cur,sum);
return sum;
}
void dfs(MapSum* cur,int &sum){
sum+=cur->val;
for(MapSum* m:cur->next)
if(m)dfs(m,sum);
}
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum* obj = new MapSum();
* obj->insert(key,val);
* int param_2 = obj->sum(prefix);
*/