优化算法

Optimising Algorithm

本文关键字:算法 优化      更新时间:2023-10-16

我需要优化这个函数,但是我不知道如何提高它的速度…

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()要求使用线性搜索算法。如果问题的根源在别处,你就无法优化。