c++ - C++中矩阵的最小值

标签 c++ vector min priority-queue multimap

我有一个 std::vector<std::vector<type T>> matrix ,我插入元素 type T到这个矩阵,我对这些元素逐行做一些说明。我还需要在每次迭代中以最低成本删除元素。

我创建了一个 std::priority_queue<Costelement, std::vector<Costelement>, Costelement::Comparekeys> Costvec;其中:

 struct Costelement
{
    int row;
    int column;
    std::vector<double> cost;

    struct CompareCosts
    {
        bool operator()(const Costelement &e1, const Costelement &e2)
        {
            return (e1.cost > e2.cost);
        }
    };
};

哪里rowcolumn是元素在 matrix 中的位置有相应的成本。但是,当我从 matrix 中删除具有最小键的元素时, 元素在相应 row 中的位置改变。我用了std::min_elementmatrix 的每次迭代中但这是非常昂贵的。我们如何才能有效地对这种情况进行建模?

最佳答案

A std::priority_queue默认情况下只是一个保持排序状态的 std::vector。从队列中插入和删除元素仍然很昂贵,正如您所注意到的,当您从 中插入或删除元素时,您可能需要更新队列中的所有 Costelements matrix 以反射(reflect)新的位置。但是,您也可以通过将优先级队列设为二维来提高效率,如下所示:

std::priority_queue<std::priority_queue<Costelement, ...>, ...> cost_matrix;

基本上,内部优先级队列对单个行的列的成本进行排序,然后外部优先级队列应该对整行的成本进行排序。让我们创建 ColumnCostRowCost 结构:

struct ColumnCost {
    int column;
    double cost;

    friend bool operator<(const ColumnCost &a, const ColumnCost &b) {
        return a.cost > b.cost;
    }
};

struct RowCost {
    int row;
    std::priority_queue<ColumnCost> columns;

    friend bool operator<(const RowCost &a, const RowCost &b) {
        return a.columns.top() > b.columns.top();
    }
};

std::priority_queue<RowCost> cost_matrix;

现在您可以轻松地从costmatrix 中获取最低成本元素,它返回包含最低成本元素的RowCost,然后您获得ColumnCost 成本最低的那个:

const auto &lowest_row = cost_matrix.top();
const auto &lowest_column = lowest_row.columns.top();
int row = lowest_row.row;
int column = lowest_column.column;

当您现在从 matrix 中插入或删除元素时,您将以相同的方式从 cost_matrix 中插入或删除元素。您仍然需要更新 rowcolumn 坐标,但现在工作量少了很多。唯一需要注意的是,如果您更新添加或删除元素到 RowCost 的优先级队列,您需要从 cost_matrix 中删除并重新插入整行code> 以确保外部优先级队列保持正确排序。

另一种可能的优化是使用 std::priority_queue 来保持行排序,但使用 std::min_element() 来跟踪每个行的最小值个人行。这大大减少了存储 cost_matrix 所需的内存量,并且您只需要调用 std::min_element() 来重新计算行的最小成本元素你改变那一行。

关于c++ - C++中矩阵的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67890667/

相关文章:

范围子集的 excel 最小值

c++ - 如何使用 unordered_set?

c++ - SPOJ 错误答案

c++ - 在 cocos2d-x 上使用参数从 Object-C 到 C++ 的函数回调

arrays - 根据其内容将向量拆分为多个向量

sql - 如何将条件传递给 SQL 中的 MINI 语句

c++ - 以相反的顺序迭代可变模板参数

python - 在gensim中创建一个新的矢量模型

多维数组的Java序列化

python - 为数据框中的每一行查找 n 个最低值