简单方法:
#include<bits/stdc++.h> using namespace std; int main() { char s[100]; map<string,int>ma; while(gets(s)&&strlen(s)!=0) { for(int i=strlen(s)-1;i>=0;i--) { ma[s]++; s[i]='\0'; // cout<<s<<endl; } } while(gets(s)) { printf("%d\n",ma[s]); } }
但是当数据过多的时候map就不行了
要用新的数据结构——字典树
有两种实现的方法 一种是指针 一种是数组
数组的实现方法更为方便 高明 快速
注意 数组一定要开到一百万 不然wa !!!
#include<bits/stdc++.h> using namespace std; int trie[1000010][26]={0}; int sum[1000010]={0}; int pos=0; void insert1( char *word ) { int root=0; for(int i=0;i<strlen(word);i++) { int ch=word[i]-'a'; if(trie[root][ ch ]==0) trie[root][ ch ]=++pos; root=trie[root][ch]; sum[root]++; } } int find1(char *word) { int root=0; for(int i=0;i<strlen(word);i++) { int ch=word[i]-'a'; if(trie[root][ ch ]==0)return 0; root=trie[root][ch]; } return sum[root]; } int main() { char word[15]; while(gets(word)) { if(strlen(word)==0)break; insert1(word); } while(gets(word)) { printf("%d\n",find1(word)); } }