优化算法
Optimising Algorithm
我需要优化这个函数,但是我不知道如何提高它的速度…
bool generateShortestpathLink (const string& start, const string& finish, const book& db) {
vector <lib> bks;
vector <string> authors;
set <lib> storeBKS;
set <string> storeAuthor;
queue <pathLink> q;
pathLink p(start);
q.push(p);
while (!q.empty()) {
p = q.front();
if (p.getLength() > 6) return false;
db.getTitles(p.getLastPlayer(), bks);
for (int x = 0; x < (int) bks.size(); x++) {
const film& newBook = bks[x];
if (storeBKS.find(newBook) != storeBKS.end()) continue;
db.getAuthors(newBook, authors);
storeBKS.insert(newBook);
for (int i = 0; i < (int) authors.size(); i++) {
if (storeAuthor.find(authors[i]) != storeAuthor.end()) continue;
pathLink newpathLink(p);
newpathLink.addConnection(newBook, authors[i]);
if (authors[i] == finish) return true;
storeAuthor.insert(authors[i]);
q.push(newpathLink);
}
}
q.pop();
}
return false;
}
它应该是BFS的算法,它创建用于连接不同书名和作者的路径。getTitles()
和getAuthors
都是不能修改的二分查找函数。有人能帮我一下吗?
我看到的第一件事是您没有预先分配任何内存。这是优化算法时要做的第一件事,因为你不能改变算法。您应该找出这些结构将需要多少内存,并立即分配所有内存,以防止它们必须反复重新分配。
另外,考虑使用排序向量而不是set
。这将大大提高查找时间——只是不要太频繁地插入,否则会受伤。
您已经明确排除了最大的优化,说getTitles()
不能被触及。你有一个循环中的循环。中间的循环似乎是罪魁祸首。实际上,getTitles()
要求使用线性搜索算法。如果问题的根源在别处,你就无法优化。
相关文章:
- std::stable_sort: 如何选择内存优化算法而不是时间优化算法?
- 解析参数后内联以优化算法速度
- 如何优化标准::设置交集算法(C++)
- 优化的图像卷积算法
- 优化德劳奈三角测量算法
- 优化查找特定斐波那契数的算法
- 基本算法优化
- "Neighbor function"优化以使用A*算法解决8难题
- 优化算法以查找满足某些属性的六位数字的数量
- 利用优先级队列C++优化了从O(n^2)到O(n)的Huffman树算法
- STL算法是否针对速度进行了优化
- 优化最近邻居大小调整算法以提高速度
- 用于优化存储/运行时算法的元编程,C++
- 如何进一步优化这个简单的算法
- 优化 pow 算法
- 优化算法"binary_fold"并使其左(或右)关联
- 算法优化
- C++算法优化:从N个元素中求出K组合
- 如何优化随机排序算法
- 算法优化-有n个除数的最小数