题目描述

给一个字符串, 然后给一个字典。 把字符串分解成字典里的单词组成的句子, 请输出所需空格最少的方案。并输出该方案。

样例

例如: 字符串为: str="ilikealibaba", 字典为dict= {"i", "like", "ali", "ba", "alibaba", "baba"}

输入:
ilikealibaba
6
i
like
ali
ba
alibaba
baba 输出:
i like alibaba

解题思路:

空格最少,很显然用BFS应该可以做。 不过状态转移的时候需要写个小函数, 另外由于需要打印路径,所以要记录一下路径。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include <stdexcept>
#include <cstring>
using namespace std; struct Node
{
string word; // 当前匹配过的单词
int pos; // 记录下一个要匹配的位置
string path; // 记录路径
}; int matchW(const string& str, int pos, const string word)
{
for(int i = 0; i < word.size(); i++)
{
if(pos >= str.size())
return -1;
if(str[pos++] != word[i])
return -1;
} return pos;
} void mincut(const string& str, const set<string>& dict)
{
if(str.size() == 0)
{
printf("n/a\n");
return;
} queue<Node> qu;
for(auto it : dict)
{
int tmp = matchW(str, 0, it);
if(tmp != -1) // 该单词是否能匹配
{
Node tt;
tt.word = it;
tt.pos = tmp;
tt.path += it;
qu.push(tt);
}
} while(!qu.empty())
{
int len = qu.size();
while(len--)
{
Node tt = qu.front();
qu.pop();
if(tt.pos == str.size()) // 已匹配完成
{
cout << tt.path << endl; // 打印路径
return;
} for(auto it : dict)
{
int tmp = matchW(str, tt.pos, it);
if(tmp != -1)
{
Node gg;
gg.word = it;
gg.pos = tmp;
gg.path = tt.path + " " + it;
qu.push(gg);
}
}
}
} printf("n/a\n");
} int main(int argc, const char * argv[])
{
string strS;
string dictStr;
int nDict;
set<string> dict; cin>>strS;
cin>>nDict;
for (int i = 0; i < nDict; i++)
{
cin>>dictStr;
dict.insert(dictStr);
}
mincut(strS, dict); return 0;
}

最新文章

  1. 记得初学JS时候练个九九乘法表都写的要死要活
  2. n+1 &lt; n , are you sure?
  3. mongodb certification
  4. 一点简单的关于ASP.NET下载
  5. 234. Palindrome Linked List
  6. 关于asp.net C# 导出Excel文件 打开Excel文件格式与扩展名指定格式不一致的解决办法
  7. HDU-1978How many ways
  8. HDU 1847 Good Luck in CET-4 Everybody!
  9. nodejs中http-proxy使用小结
  10. pytorch torch.Storage学习
  11. hdu 2159 FATE (二维完全背包)
  12. Unity3D使用EasyMovieTexture插件播放视频
  13. 观察者模式(Observer Pattern)
  14. Android开发之实现多次点击事件
  15. iBatis resultMap报错 nullValue完美解决
  16. 2018-2019-2 网络对抗技术 20165301 Exp4 恶意代码分析
  17. pom.xml设置maven的编码方式
  18. oracle 将逗号分隔的字符串转成多行记录
  19. 如何在Windows环境搭建Object C开发环境
  20. Python开发【Django】:缓存、信号

热门文章

  1. Python全栈day10(运算符)
  2. Android Handler 的使用
  3. googlr 黄金法则 监控
  4. 二项分布。计算binomial(100,50,0.25)将会产生的递归调用次数(算法第四版1.1.27)
  5. HDFS基本命令行操作及上传文件的简单API
  6. Period II---fzu1901(Next数组)
  7. app瘦身和包压缩技术有什么区别?
  8. sql之密码保存
  9. NAND flash阵营ToggleDDR和ONFI
  10. PHP 基础篇 - PHP 中 DES 加解密详解