题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=290
经典的字典树的问题,代码几乎可以来当模版来用了,就留下来了~~~,不过貌似用运算符重载排序(不知道是不是)也能过。。。。。。。。需要注意的是开辟一个新的内存时下一个指针一定要指向NULL;
字典树代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int max;
char ans[101];
struct node
{
int count;/*计数器*/
struct node *next[26];/*指向下一个26个字母*/
};
struct node *root;/*建立头节点*/
struct node *newset()/*建立新节点*/
{
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
for(int i=0;i<26;i++)
{
p->next[i]=NULL;/*开辟节点*/
}
p->count=0;/*计数器初始化为0*/
return p;/*新建完成*/
}
void insert(char *s)/*建立字典树*/
{
struct node *p;
//p=(struct node *)malloc(sizeof(struct node));这里只是需要个指针,再开内存就要超了。。。。。
p=root;/*p开始指向头结点*/
int len=strlen(s);
for(int i=0;i<len;i++)
{
if(p->next[s[i]-'a']==NULL)
{
p->next[s[i]-'a']=newset();/*建立节点*/
}
p=p->next[s[i]-'a'];
}
p->count++;
if(p->count>max)
{
max=p->count;
strcpy(ans,s);
}
}
int main()
{
int ncases;
char str[20];
root=newset();
scanf("%d",&ncases);
while(ncases--)
{
scanf("%s",str);
insert(str);
}
printf("%s %d\n",ans,max);
return 0;
}
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int max;
char ans[101];
struct node
{
int count;/*计数器*/
struct node *next[26];/*指向下一个26个字母*/
};
struct node *root;/*建立头节点*/
struct node *newset()/*建立新节点*/
{
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
for(int i=0;i<26;i++)
{
p->next[i]=NULL;/*开辟节点*/
}
p->count=0;/*计数器初始化为0*/
return p;/*新建完成*/
}
void insert(char *s)/*建立字典树*/
{
struct node *p;
//p=(struct node *)malloc(sizeof(struct node));这里只是需要个指针,再开内存就要超了。。。。。
p=root;/*p开始指向头结点*/
int len=strlen(s);
for(int i=0;i<len;i++)
{
if(p->next[s[i]-'a']==NULL)
{
p->next[s[i]-'a']=newset();/*建立节点*/
}
p=p->next[s[i]-'a'];
}
p->count++;
if(p->count>max)
{
max=p->count;
strcpy(ans,s);
}
}
int main()
{
int ncases;
char str[20];
root=(struct node *)malloc(sizeof(struct node));//newset();
for(int i=0;i<26;i++)
{
root->next[i]=NULL;/*开辟节点*/
}
root->count=0;/*计数器初始化为0*/
scanf("%d",&ncases);
while(ncases--)
{
scanf("%s",str);
insert(str);
}
printf("%s %d\n",ans,max);
return 0;
}
运算符重载代码:(这个要比sort跟qsort排序要快。。。。。)
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct tj
{
char str[11];
int count;
}w[4000001];
bool operator<(tj const&x,tj const&y)
{
if(strcmp(x.str,y.str)<0) return true;
return false;
}
int main()
{
int n,i,j,p,max;
memset(w,0,sizeof(w));
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%s",w[i].str);
w[i].count=1;
}
sort(w,w+n);
p=0;max=0;
for(i=1;i<n;i++)
{
if(strcmp(w[i].str,w[i-1].str)==0)
{
w[i].count=w[i-1].count+1;
}
if(w[i].count>max)
{
max=w[i].count;
p=i;
}
}
printf("%s %d\n",w[p].str,max);
return 0;
}