ArticleDirectory
- Problem
- Input
- Output
- Sample Input
- Sample output
Problem
There is a long string consisting of lowercase letters. To facilitate the analysis of this string, you need to divide it into several parts, each of which is called a word.
To reduce the analysis volume, we hope that the fewer words we divide, the better. You are here to complete this division.
Input
The first behavior is an integer T, indicating that there are T groups of test data.
The first behavior of each group of test data is a string. (Length less than 256)
The second behavior is an integer n. (1 <= n <= 100)
The following n rows have one word per line.
Output
An integer that represents the minimum number of words that a string can be divided.
Sample Input
1
Realityour
5
Real
Reality
It
Your
Our
Sample output
2
Code:
# Include <cstdio>
# Include <cstring>
# Include <set>
# Include <functional>
Using namespace STD;
Enum {max_len = 256 };
Struct Sless: Public binary_function <const char *, const char *, bool>
{
Bool operator () (const char * S1, const char * S2) const
{
Return strcmp (S1, S2) <0;
}
};
Int split_string (char * s, const set <const char *, Sless> & words)
{
If (S = 0)
Return 0;
Int M [max_len] = {0 };
Int Len = strlen (s );
For (INT I = 0; I <Len; ++ I)
{
Char CH = s [I + 1];
S [I + 1] = 0;
If (words. Find (s )! = Words. End ())
M [I] = 1;
Else
{
Int minimum = int_max;
For (Int J = I; j> 0; -- J)
{
If (M [J-1]! = 0 & words. Find (S + J )! = Words. End ())
Minimum = min (M [J-1] + 1, minimum );
}
M [I] = minimum;
}
S [I + 1] = CH;
}
Return M [len-1];
}
Int main ()
{
# If 0 // for lazy Testing
Char s [] = "realityour ";
Const char * words [] =
{
"Real ",
"Reality ",
"It ",
"Your ",
"Our ",
0
};
Set <const char *, Sless> ws;
For (INT I = 0; words [I]! = 0; ++ I)
WS. insert (words [I]);
Int result = split_string (S, WS );
Printf ("Result: % d \ n", result );
# Endif
Int size;
Scanf ("% d", & size );
For (INT I = 0; I <size; ++ I)
{
Char s [max_len] = {0 };
Scanf ("% s", S );
Int num;
Scanf ("% d", & num );
Set <const char *, Sless> ws;
For (Int J = 0; j <num; ++ J)
{
Char * In = new char [128];
Memset (in, 0,128 );
Scanf ("% s", in );
WS. insert (in );
}
Printf ("% d \ n", split_string (S, WS ));
}
}