hdu 1251 統計難題
字典樹模板題。
#include <bits/stdc++.h>
using namespace std;
const int N=1e6+10;//開大一點,否則RE
char s[N];
int num,cnt[N],ch[N][30];
void build(char s[])
{
int u=0;
for(int i=0;i<strlen(s);i++)
{
int x=s[i]-'a';
if(!ch[u][x])ch[u][x]=++num;
u=ch[u][x];
cnt[u]++;
}
}
int query(char s[])
{
int u=0;
for(int i=0;i<strlen(s);i++)
{
int x=s[i]-'a';
if(!ch[u][x])return 0;
u=ch[u][x];
}
return cnt[u];
}
int main()
{
ios::sync_with_stdio(false);
while(gets(s)&&s[0]!='\0')//用gets處理空行,如果是空行,gets會自動把'\n'轉化爲'\0'
build(s);
while(gets(s)&&s[0]!='\0')printf("%d\n",query(s));
//雖然是處理到文件末尾,但是不能寫成while(cin>>s),否則會WA(不知道爲什麼...)
return 0;
}
hdu 1671 Phone List
給你n個字符串,如果存在一個字符串是其他某個字符串的前綴,則輸出NO,否則輸出YES。
#include <bits/stdc++.h>
using namespace std;
const int N=1e4+10,M=1e5+10;
string a[N];
int t,n,num,cnt[M],ch[M][10];
bool cmp(string s1,string s2)
{return s1<s2;}
int build(string s)
{
int u=0;
for(int i=0;i<s.length();i++)
{
int x=s[i]-'0';
if(cnt[u])return 1;
if(!ch[u][x])ch[u][x]=++num;
u=ch[u][x];
}
cnt[u]++;
return 0;
}
int main()
{
ios::sync_with_stdio(false);
cin>>t;
while(t--)
{
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
sort(a+1,a+n+1,cmp);
memset(ch,0,sizeof(ch));
memset(cnt,0,sizeof(cnt));
num=0;
int flag=0;
for(int i=1;i<=n;i++)
{
int tmp=build(a[i]);
if(tmp==1){printf("NO\n");flag=1;break;}
}
if(flag==0)printf("YES\n");
}
return 0;
}
hdu 2072 單詞數
分割單詞,再構造字典樹即可。
注意特判 全是空格 的情況。
要注意一下輸入字符串的格式。
跳過空格輸入可以用 gets(a) 或者 scanf("%[^\n]",a)
while(scanf("%[^\n]",a))無法while循環,因爲第一次遇到 \n 程序就停止了。
可以寫 while(scanf("%[^\n]%*c",a)), 與 while(gets(a)) 等效。
%*c表示跳過一個字符,也就是把 \n 吸收掉。
也可以寫 while(scanf("%[^\n]",a)),內循環加一句 getchar() 來吸收 \n 字符。
(所以說爲什麼不直接寫gets(a)?)
關於while(scanf("%[^\n]%*c",a))
輸入,具體的原理可以看看這篇文章:https://blog.csdn.net/weixin_43469047/article/details/83753526
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+10;
char a[N],s[N];
int num,tot,ans,cnt[N],ch[N][30];
void build(char s[])
{
int u=0;
for(int i=1;i<=tot;i++)
{
int x=s[i]-'a';
if(!ch[u][x])ch[u][x]=++num;
u=ch[u][x];
}
cnt[u]++;
if(cnt[u]==1)ans++;
}
int main()
{
ios::sync_with_stdio(false);
while(gets(a)&&a[0]!='#')//注意用gets(a),不要用scanf(" %[^\n]",a),否則會錯
{
memset(s,0,sizeof(s));
memset(ch,0,sizeof(ch));
memset(cnt,0,sizeof(cnt));
tot=0;num=0;ans=0;
for(int i=0;i<strlen(a);i++)
{
if(a[i]!=' ')
{
s[++tot]=a[i];
if(a[i+1]==' '||a[i+1]=='\0')
{
build(s);
memset(s,0,sizeof(s));
tot=0;
}
}
}
printf("%d\n",ans);
}
return 0;
}