IME HDU-4287-Intelligent
Http://acm.hdu.edu.cn/showproblem.php? Pid = 1, 4287
Start to use dictionary tree + deep search, timeout .... Later, we found that the question can contain a maximum of six digits. We can convert the string into a corresponding number, and then hash it.
TLE code
[Cpp]
# Include <iostream>
# Include <cstdio>
# Include <cstring>
# Include <cstdlib>
Using namespace std;
Int n, m, ans;
Char map [5005] [8];
Char word [8];
Char phone [8] [4] = {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 10, 11}, {12, 13, 14 }, {, 17,18}, {, 21}, {, 24, 25 }};
Int num [8] = {3, 3, 3, 3, 3, 4, 3 };
Struct node
{
Int count;
Node * childs [26];
Node ()
{
Count = 0;
For (int I = 0; I <26; I ++)
Childs [I] = NULL;
}
};
Node * root;
Node * current, * newnode;
Void insert (char * str) // insert a string
{
Int I, m;
Current = root;
For (I = 0; I <strlen (str); I ++)
{
M = str [I]-'A ';
If (current-> childs [m]! = NULL)
Current = current-> childs [m];
Else
{
Newnode = new node;
Current-> childs [m] = newnode;
Current = newnode;
}
}
Current-> count = 1;
}
Int search (char * str) // search for the existence of a word in the dictionary tree
{
Int I, m;
Current = root;
For (I = 0; I <strlen (str); I ++)
{
M = str [I]-'A ';
If (current-> childs [m] = NULL)
Return 0;
Current = current-> childs [m];
}
Return current-> count;
}
Void del (node * head)
{
Int I;
For (I = 0; I <26; I ++)
If (head-> childs [I]! = NULL)
Del (head-> childs [I]);
Delete (head );
}
Void dfs (char str [10], int len, int t)
{
Int I, s;
If (t = len)
{
Word [len] = '\ 0 ';
If (search (word ))
Ans ++;
}
S = num [str [t]-'2'];
For (I = 0; I <s; I ++)
{
Word [t] = phone [str [t]-'2'] [I] + 'a ';
Dfs (str, len, t + 1 );
}
}
Int main ()
{
Int t, I;
Int len;
Char temp [8];
Scanf ("% d", & t );
While (t --)
{
Scanf ("% d", & n, & m );
For (I = 0; I <n; I ++)
Scanf ("% s", map [I]);
Root = new node;
While (m --)
{
Scanf ("% s", temp );
Insert (temp );
}
For (I = 0; I <n; I ++)
{
Ans = 0;
Len = strlen (map [I]);
Dfs (map [I], len, 0 );
Printf ("% d \ n", ans );
}
Del (root );
}
Return 0;
}
AC code
[Cpp]
# Include <stdio. h>
# Include <string. h>
# Include <stdlib. h>
Int hashh [1000005];
Int a [5005];
Char str [10];
Int judge (char c)
{
If ('A' <= c & c <= 'C ')
Return 2;
Else if ('D' <= c & c <= 'F ')
Return 3;
Else if ('G' <= c & c <= 'I ')
Return 4;
Else if ('J' <= c & c <= 'l ')
Return 5;
Else if ('M' <= c & c <= 'O ')
Return 6;
Else if ('P' <= c & c <='s ')
Return 7;
Else if ('T' <= c & c <= 'V ')
Return 8;
Else if ('W' <= c & c <= 'Z ')
Return 9;
}
Int main ()
{
Int t;
Int I, j, n, m, len, sum;
Scanf ("% d", & t );
While (t --)
{
Scanf ("% d", & n, & m );
For (I = 0; I <n; I ++)
Scanf ("% d", & a [I]);
Memset (hashh, 0, sizeof (hashh ));
For (I = 1; I <= m; I ++)
{Www.2cto.com
Scanf ("% s", str );
Len = strlen (str );
Sum = 0;
For (j = 0; j <len; j ++)
Sum = sum * 10 + judge (str [j]);
Hashh [sum] ++;
}
For (I = 0; I <n; I ++)
Printf ("% d \ n", hashh [a [I]);
}
Return 0;
}