【编程题】2018阿里编程题题一
来源:互联网 发布:担保公司业务软件 编辑:程序博客网 时间:2024/06/10 01:05
转化为最短路径搜索:
将D中存储的词看为一条路径:如”like”表示“ilikealibaba”中存在一条从S[1]: “l”直接到S[5]: “a”的路径。
则最少空格数的解就是从S[0]走到S[n]最短路径的解。
测试样例中存在两条路径:
1: S[0]->S[1]->S[5]->S[7]->S[12]
2: S[0]->S[1]->S[5]->S[12]
最短路径使用BFS
#include <stdio.h>#include <vector>#include <numeric>#include <algorithm>#include <iostream>#include <string>#include <set>#include <regex>#include <queue>using namespace std;//#define debug_void mincut(const string& str, const set<string>& dict){ vector<vector<int>> path_map(str.size()); vector<int> cost(str.size()+1,99999); int strSize = str.size(); for (auto i = 0; i < str.size();++i) { for (auto iter = dict.begin(); iter != dict.end();iter++) { if (str.substr(i,(*iter).size()) == *iter) { path_map[i].push_back(i+(*iter).size()); } } } queue<int> que; que.push(0); cost[0] = 0; while (!que.empty()) { int s = que.front(); que.pop(); for (auto i = 0; i < path_map[s].size();++i) { if (cost[s]+1<cost[path_map[s][i]]) { if (path_map[s][i] != strSize)//不是终点 { que.push(path_map[s][i]); } cost[path_map[s][i]] = cost[s] + 1; } } } int cur_index(strSize); vector<string> print_vec; if (cost[strSize] == 99999) { cout <<"n/a"; return; } for (auto i = strSize; i >= 0;--i) { if (cost[i] + 1 == cost[cur_index]) { string tmp = str.substr(i, cur_index-i); print_vec.push_back(tmp); cur_index = i; } } for (auto iter = print_vec.rbegin(); iter != print_vec.rend();iter++) { cout << *iter << " "; }}int main(int argc, const char * argv[]){ string strS; string dictStr; int nDict; set<string> dict;#ifdef debug_ strS = "ilikealibaba"; dict.insert("i"); dict.insert("like"); dict.insert("ali"); dict.insert("liba"); dict.insert("baba"); dict.insert("alibaba");#else cin >> strS; cin >> nDict; for (int i = 0; i < nDict; i++) { cin >> dictStr; dict.insert(dictStr); }#endif mincut(strS, dict); return 0;}
阅读全文
0 0
- 【编程题】2018阿里编程题题一
- 阿里编程题
- 阿里编程测验题
- 阿里2018校招笔试编程题
- 阿里2018校招编程题
- 阿里前端编程题1
- 阿里实习生编程题2
- 阿里实习编程题1
- 2017阿里编程测试题
- 阿里秋招编程题
- 阿里2017编程笔试题
- 阿里2017年秋招编程题
- 2018秋招-阿里内推编程题
- 阿里2018测评编程题——小明购物。。。
- 阿里2018校招客户端研发笔试之编程题
- 阿里2018届应届生招聘JAVA编程题
- 2018届秋招提前批阿里在线编程
- 阿里校园招聘2017编程题
- 开发一个基于ZXing库以及安卓Studio的二维码扫描小程序(二)
- Kafka配置SSL(云环境)
- 临时解决 cat 打开中文乱码
- CSDN--Markdown语法
- Django分析之使用redis缓存服务器
- 【编程题】2018阿里编程题题一
- 编译安装vim8.0
- Linux开发工具(gcc gdb make shell)——GCC中-I -L -l区别
- Visual Assist实现*.h和*.cpp的函数声明和定义的同步。
- Leetcode#35: Search Insert Position
- 打印倒三角形*,包含最后一颗*
- 数字信号处理——图像篇
- poj 1836
- spark源码分析之DAGScheduler提交作业(job)过程、stage阶段说明