相信很多人都做过这题目,你可以完全当做这是一条水题,但是最近在搞TRIE,就用TRIE来做。
首先,用map一次水掉了,不解释,当然也可以自己写一个map,如编程珠玑统计圣经单词那样做,一摸一样。
#include<iostream> #include<map> #include<cstring> #include<string> #include<cstdio> using namespace std; int main(){ int n,i; char str[30]; map<string,int> mp; while(scanf("%d",&n)&&n){ mp.clear(); for(i=0;i<n;i++){ scanf(" %s",str); mp[str]++; } map<string,int>::iterator itr=mp.begin(); int max=-1; string sb=""; while(itr!=mp.end()){ //cout<<itr->second; if(itr->second>max){ max=itr->second; sb=itr->first; } itr++; }; cout<<sb<<endl; } return 0; }
10569813 | 2014-04-18 15:54:39 | Accepted | 1004 | 15MS | 284K | 585 B | C++ | deron |
后来,我就拿着自己的trie树模板在改了,改了好多次,终于觉得没问题了,还是WA……
因为,其实我从来不会用char *,这次用了char * s,char sb[];s=sb,这样导致一直WA……为什么?我也不知道啊,我能说我从来都是用string么(求大神指导)……
后来,用了strcpy,第一次用啊……感觉自己好弱。
马上就AC了,世界就是这么神奇……
为什么乱码……今天开得是VC6,每次打开在linux写的就会这个样子……懒得改了,大家可以YY……
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<cstdlib> using namespace std; template<int Size> struct trie_node{ bool terminable; //??????????? int node; //?????? int cnt; trie_node *child[Size]; //???? trie_node():terminable(false), node(0),cnt(0){ memset(child,0,sizeof(child)); //????? } }; int maxN; char sb[30]; char s[30]; template<int Size,typename Index> class trie{ public: //???? typedef trie_node<Size> node_type; typedef trie_node<Size> *link_type; //???? trie(Index i=Index()):index(i){ } //????,???? void clear(){ clear_node(root); for(int i=0;i<Size;i++) root.child[i]=0; } //?? template<typename Iterator> bool insert(Iterator begin,Iterator end){ link_type cur= &root;//???????? while(begin!=end){ if(!cur->child[index[*begin]]){//??? cur->child[index[*begin]]=new node_type; cur->node++; } cur=cur->child[index[*begin]]; begin++; //??????! } cur->terminable=true; cur->cnt++; if(cur->cnt> maxN){ maxN=cur->cnt; // cout<<maxN; return true; } return false; } //??c???? void insert( char * str){ if(insert(str,str+strlen(str))){ strcpy(sb,str); }; } private: //?? void clear_node(node_type cur){ for(int i=0;i<Size;i++){ if(cur.child[i]==0)continue; //??? clear_node(*cur.child[i]); delete cur.child[i]; cur.child[i]=0; if(--cur.node==0) break; //????? } } //? node_type root; //?????,??hash Index index; }; class IndexClass{ public: int operator[](const char key){ return key%26; //???? } }; int main(){ trie<26,IndexClass> t; //freopen("in.txt","r",stdin); int n; while(scanf("%d",&n)&&n) { maxN=-1; for(int i=0;i<n;i++){ scanf("%s",s); t.insert(s); // cout<<maxN<<endl; } printf("%s\n",sb); t.clear(); } return 0; }