当前位置: 代码迷 >> 综合 >> 【HDU 2072 单词数】 字典树/SET
  详细解决方案

【HDU 2072 单词数】 字典树/SET

热度:63   发布时间:2023-12-29 02:54:21.0

HDU2072
题意就是出现的不同单词个数
直接把字符全部插入Trie树中,然后统计所有具有flagg标记的节点个数就好了。
也可以边插入边统计,如果当前字符串结尾下标已经被标记,就不对答案做贡献,否则ans++.
HDU 2072 代码

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<sstream>
using namespace std;
const int maxn =2e6+5;
int tree[maxn][30];
bool flagg[maxn];
int tot;
void insert_(string str)
{int len=str.size();int root=0;for(int i=0;i<len;i++){int id=str[i]-'a';if(!tree[root][id]) tree[root][id]=++tot;root=tree[root][id];}flagg[root]=true;
}
bool find_(string str)
{int len=str.size();int root=0;for(int i=0;i<len;i++){int id=str[i]-'a';if(!tree[root][id]) return true;//该单词没有出现过root=tree[root][id];}if(flagg[root]) return false;//出现过,不再算贡献else return true;
}
string str1,str2;
int main()
{ios::sync_with_stdio(false);while(getline(cin,str1)){if(str1=="#") break;int ans=0;stringstream ss(str1);while(ss>>str2){if(find_(str2)){ans++;insert_(str2);}}cout<<ans<<endl;for(int i=0;i<tot;i++){flagg[i]=false;for(int j=0;j<30;j++)tree[i][j]=0;}tot=0;}return 0;
}