给定一组单词,和一个起始单词,寻找有该单词每次添加一个字母都能构成该单词组中的某个单词,求能够成的最长的单词。采用队列实现的广搜方法,先将单词按长度排列,从起始单词的长度开始,对于每一个可能的单词放入队列,然后从长度比它大一的单词中找是否存在有它构成的,有放入序列,继续,直到队列为空。
Source:
#include
<
map
>
#include < queue >
#include < string >
#include < algorithm >
#include < iostream >
using namespace std;
int cmp( const void * a, const void * b);
int mx;
string sa,str,res;
string data[ 1010 ];
map < string , bool > dic;
queue < string > q;
int main()
{
int i,j,k,len,ls,le,n;
string c;
cin >> n >> sa;
for (i = 0 ;i < n; ++ i)
{
cin >> str;
dic[str] = false ;
data[i] = str;
}
qsort(data,n, sizeof ( string ),cmp);
// for(i=0;i<n;++i)cout<<data[i]<<endl;
q.push(sa);
mx = 0 ;
while ( ! q.empty())
{
c = q.front();
len = c.length();
// cout<<c<<endl;
if (len > mx)
{
mx = len;
res = c;
}
q.pop();
len ++ ;
for (ls = 0 ;ls < n && data[ls].length() < len; ++ ls);
for (le = ls;le < n && data[ls].length() == len; ++ le);
for (i = ls;i < le; ++ i)
{
if (dic[data[i]]) continue ;
for (j = 0 ,k = 0 ;j < len + 1 ; ++ j)
{
if (data[i][j] == c[k]) ++ k;
}
if (k == len)
{
q.push(data[i]);
dic[data[i]] = true ;
}
}
}
cout << res << endl;
return 0 ;
}
int cmp( const void * a, const void * b)
{
return ( * (( string * )a)).length() - ( * (( string * )b)).length();
}
#include < queue >
#include < string >
#include < algorithm >
#include < iostream >
using namespace std;
int cmp( const void * a, const void * b);
int mx;
string sa,str,res;
string data[ 1010 ];
map < string , bool > dic;
queue < string > q;
int main()
{
int i,j,k,len,ls,le,n;
string c;
cin >> n >> sa;
for (i = 0 ;i < n; ++ i)
{
cin >> str;
dic[str] = false ;
data[i] = str;
}
qsort(data,n, sizeof ( string ),cmp);
// for(i=0;i<n;++i)cout<<data[i]<<endl;
q.push(sa);
mx = 0 ;
while ( ! q.empty())
{
c = q.front();
len = c.length();
// cout<<c<<endl;
if (len > mx)
{
mx = len;
res = c;
}
q.pop();
len ++ ;
for (ls = 0 ;ls < n && data[ls].length() < len; ++ ls);
for (le = ls;le < n && data[ls].length() == len; ++ le);
for (i = ls;i < le; ++ i)
{
if (dic[data[i]]) continue ;
for (j = 0 ,k = 0 ;j < len + 1 ; ++ j)
{
if (data[i][j] == c[k]) ++ k;
}
if (k == len)
{
q.push(data[i]);
dic[data[i]] = true ;
}
}
}
cout << res << endl;
return 0 ;
}
int cmp( const void * a, const void * b)
{
return ( * (( string * )a)).length() - ( * (( string * )b)).length();
}