HDU1004 Let the Balloon Rise【字典树】

来源:互联网 发布:网络错误错误代码0031 编辑:程序博客网 时间:2024/06/08 22:05

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1004


题目大意:

ACM比赛要统计所有队伍最初哪道题的数量最多。给你N个代表气球颜色的字符串。输出出现

次数最多的气球颜色。题目保证每组数据结果是唯一的。


思路:

有两种方法来做。

1)可以用普通的二维字符串数组存放气球颜色,然后两重for循环求出每个气球的个数。用一个

数组存放每个气球的个数。最后求出个数最多的气球,输出字符串。

2)用字典树将所有的气球颜色字符串存起来,并统计字符串出现的次数。然后找到最多的气球字

串,进行输出。


AC代码:

普通方法:

# include<stdio.h># include<string.h>char a[1010][18];int b[1010];int main(){    int n,i,j,max;            while(scanf("%d",&n) && n!=0)    {        max = 0;        memset(a,0,sizeof(a));        memset(b,0,sizeof(b));        getchar();        for(i=0;i<n;i++)        {            scanf("%s",a[i]);        }        for(i=0;i<n;i++)        {            for(j=i+1;j<n;j++)            {                if(strcmp(a[i],a[j])==0)                    b[i]++;            }        }        for(i=0;i<n;i++)        {            if(b[i]>max)                max=b[i];        }        for(i=0;i<n;i++)        {            if(max==b[i])                printf("%s\n",a[i]);        }    }    return 0;}
字典树方法:

#include<iostream>#include<algorithm>#include<cstdio>#include<cstring>using namespace std;struct TrieNode{    int Count;    struct TrieNode* Next[26];};TrieNode *root;void Create(){    root = new TrieNode;    memset(root->Next,NULL,sizeof(root->Next));    root->Count = 0;}void Insert(char *s){    TrieNode *p, *q;    p = root;    while(*s)    {        if(p->Next[*s-'a'] == NULL)        {            q = new TrieNode;            memset(q->Next,NULL,sizeof(q->Next));            q->Count = 1;            p->Next[*s-'a'] = q;        }        else            p->Next[*s-'a']->Count++;        p = p->Next[*s-'a'];        s++;    }}int Find(char *s){    TrieNode *p,*q;    p = root;    while(*s)    {        if(p->Next[*s-'a'] == NULL)            return 0;        p = p->Next[*s-'a'];        s++;    }    return p->Count;}char s[1100][20];int main(){    int N,M;    while(cin >> N && N)    {        Create();        for(int i = 0; i < N; ++i)        {            cin >> s[i];            Insert(s[i]);        }        int Num,pos = 0,Max = 0;        for(int i = 0; i < N; ++i)        {            Num = Find(s[i]);            if(Num > Max)            {                Max = Num;                pos = i;            }          }        cout << s[pos] << endl;    }    return 0;}



0 0
原创粉丝点击