HDU 1800(Flying to the Mars)

 

题目链接地址:http://acm.hdu.edu.cn/showproblem.php?pid=1800

思路:仔细分析容易发现,其实就是求给定的字符串中出现最多的字符串个数,当用字符串实现时,注意前导0需去掉。

方法一:map 这里为什么用map<int,int>可以,我想可能是因为虽然有的数超出范围但是读入的时候还是会读出一个数的(虽然这个数不是原来的那个数),而每个数都唯一,让然用map<string,int>似乎更合乎情理

#include<stdio.h> 
#include<iostream>
#include<map> 
using namespace std; 
int main() 
{ 
    //freopen("1002.txt","r",stdin);
    int i,n,max; 
    map<int,int>mp; 
    map<int,int>::iterator it;
    while(scanf("%I64d",&n)!=EOF) 
    { 
        mp.clear(); 
        while(n--) 
        { 
            scanf("%d",&i); 
            mp[i]++; 
        } 
        max=0; 
        for(it=mp.begin();it!=mp.end();it++) 
            if(max<it->second) max=it->second; 
            printf("%d\n",max); 
    } 
    return 0; 
}


方法二:用字符串数组,排序然后在求出现相同字符串最多的数

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
#define maxn 3001
int n,dp[maxn];
string s1,s[maxn];
int main()
{
    //freopen("1002.txt","r",stdin);
    string :: iterator it;
    while(scanf("%d",&n) != EOF)
    {
        int i,j,maxnum = 0;
        for(i = 0; i < n; i++)
        {
            cin >> s1;
            j = 0;
            while(s1[j] == '0')  j++;
            it = s1.begin();
            s1.erase(it,it+j);
            s[i] = s1;
        }
        sort(s,s+n);
        dp[0] = 1;
        for(i = 0; i < n; i++)
        {
            if(s[i] == s[i-1]) dp[i] = dp[i-1]+1;
            else dp[i] = 1;
            if(dp[i] > maxnum)  maxnum = dp[i];
        }
        printf("%d\n",maxnum);
    }
    return 0;
}

方法三:字典树,求相同字符串出现最多的次数。

#include<iostream>
#include<string>
using namespace std;
struct Trie
{
    int n;
    Trie *next[10];
    Trie()                    //构造函数
    {
        n = 0; 
        memset(next,0,sizeof(next));
    }
};
char s[35];
int n,maxnum;
void Insert(Trie *root,char s[])
{
    Trie *p = root;
    for(int i = 0; s[i]; i++)
    {
        int j = s[i] - '0';
        if(p->next[j] == NULL) p->next[j] = new Trie();
        p = p->next[j];
    }
    p->n++;
    if(p->n > maxnum)  maxnum = p->n;
}
void Delete(Trie *root)   //释放空间
{
    for(int i = 0; i < 10; i++)
    {
        if(root->next[i])
        {
            Delete(root->next[i]);
            delete(root->next[i]);
        }
    }
    root = NULL;
}
int main()
{
    //freopen("1002.txt","r",stdin);
    while(scanf("%d",&n) != EOF)
    {
        int i;
        Trie *root = new Trie();
        maxnum = 0;
        while(n--)
        {
            char c[35];
            scanf("%s",s);
            for(i = 0; s[i]; i++)    //去前导0
                if(s[i]!='0' || !s[i+1])
                {
                    strcpy(c,&s[i]);
                    break;
                }
            Insert(root,c);
        }
        printf("%d\n",maxnum);
        Delete(root);
    }
    return 0;
}

 

 

posted @ 2012-10-31 21:27  sorryhao  阅读(256)  评论(0)    收藏  举报