Wednesday, 23 September 2015

Most wanted word (UVALive 2006, Regionals 2000 >> South Pacific)

///     Raihan Ruhin
///     CSE, Jahangirnagar University.
///     Dhaka-Bangladesh.
///     id: raihanruhin (topcoder / codeforces / codechef / uva / uvalive / spoj), 3235 (lightoj)
///     mail: raihanruhin@ (yahoo / gmail / facebook)
///     blog: ruhinraihan.blogspot.com

#include<bits/stdc++.h>
using namespace std;

#define SET(a) memset(a,-1,sizeof(a))
#define CLR(a) memset(a,0,sizeof(a))
#define PI acos(-1.0)

#define MOD 1000000007
#define MX 100010

int mx;
string ans;

struct Trie{
    int cnt;
    Trie *child[26];
    Trie()
    {
    cnt=0;
    for(int i=0;i<26;i++) child[i]=NULL;
    }
};

void insert(string s, Trie *ob)
{
    int sl=s.size();
    for(int i=0;i<sl;i++)
    {
        int val=s[i]-'a';

        if(ob->child[val]==NULL)
            ob->child[val]=new Trie();
        if(i==sl-1)
        {
            ob->child[val]->cnt++;
            if(ob->child[val]->cnt > mx)
            {

                mx=ob->child[val]->cnt;
                ans=s;
            }
        }
        ob=ob->child[val];
    }
return;
}

void delete_memory(Trie *ob)
{
    for(int i=0;i<26;i++)
    if(ob->child[i]!=NULL)
        delete_memory(ob->child[i]);
delete ob;
}

int main()
{
    ios_base::sync_with_stdio(0);cin.tie(0);
    int tc, kk=1, n, sl;
    string s;
    char ch;
    while(getline(cin, s))
    {
        Trie *root=new Trie();
        mx=0;

        while(s!="#")
        {
            string tmp="";
            sl=s.size();
            for(int i=0;i<sl;i++)
            {
                if(s[i]>='A' && s[i]<='Z')
                    s[i]=tolower(s[i]);
                if(s[i]>='a' && s[i]<='z')
                    tmp+=s[i];
                else if(tmp.size()>0)
                {
                    insert(tmp, root);
                    tmp="";
                }
            }
            if(tmp.size()>0) insert(tmp, root);
            getline(cin, s);
        }
        if(mx) cout<<setw(4)<<mx<<" "<<ans<<"\n";
        delete_memory(root);
    }
return 0;
}

No comments:

Post a Comment