DFS題目

codevs上面的單詞接龍...

腦殘了..唉..題解放這屯着..

記一下這個函數..

<string>裏面

substr(0,p)

複製子字符串,要求從指定位置開始,並具有指定的長度

#include<iostream>
#include<string>
#define MAXN 21
using namespace std;
int n;
string words[MAXN];
int count_used[MAXN];
string max_str="";
void input()
{
cin>>n;
int i;
for(i=1;i<=n;i++)
{
cin>>words[i];
count_used[i]=0;
}
cin>>words[0];
 } 
 string dragon(string str_pre,string str_lat)
 {
  int min_len=str_pre.length()>str_lat.length()?str_lat.length():str_pre.length();
  if(str_pre.length()==1){min_len++;}
  int p;
  for(p=1;p<min_len;p++)
  {
  if(str_pre.substr(str_pre.length()-p,p)==str_lat.substr(0,p))
  {string str_connected=str_pre+str_lat.substr(p);
  if(str_connected.length()>max_str.length())
  {
  max_str=str_connected;}
return str_connected;}
}
return "";
 }
 void dfs(string cur_word)
 {
  int i;
  for(i=1;i<=n;i++)
  {
  if(count_used[i]>1)
  {continue;}
  string str_connected=dragon(cur_word,words[i]);
  if(str_connected.length()==0){continue;}
  count_used[i]++;
  dfs(str_connected);
  count_used[i]--;
}
 }
 int main()
 {
  input();
  dfs(words[0]);
  cout<<max_str.length();
  return 0;
 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章