c++ - 从数组中选择至少两个元素使得它们的 GCD 为 1 且成本最小的问题的解释
问题描述
在阅读此处问题的解决方案时,我注意到在通过映射(第二次)的迭代过程中,在某些情况下,某些插入是在同一个映射中执行的(“其他”)。在这种情况下,for 循环的行为是什么?迭代是否省略了新的插入?它是否正确?
编辑:这是代码
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the minimum cost required
int getMinCost(int arr[], int n, int cost[])
{
// Map to store <gcd, cost> pair where
// cost is the cost to get the current gcd
map<int, int> mp;
mp.clear();
mp[0] = 0;
for (int i = 0; i < n; i++) {
for (auto it : mp) {
int gcd = __gcd(arr[i], it.first);
// If current gcd value already exists in map
if (mp.count(gcd) == 1)
// Update the minimum cost
// to get the current gcd
mp[gcd] = min(mp[gcd], it.second + cost[i]);
else
mp[gcd] = it.second + cost[i];
}
}
// If there can be no sub-set such that
// the gcd of all the elements is 1
if (mp[1] == 0)
return -1;
else
return mp[1];
}
解决方案
您的问题有两个部分:插入是否将 for 循环中使用的迭代器保留为有效的迭代器,如果是这样,新插入的元素是在地图中更早还是更晚?
插入映射(通过operator[]
不会使迭代器无效,因此编译器为第二个 for 循环生成的迭代器在添加新元素后仍然有效。
因为最大公约数总是小于或等于两个数,所以新插入的元素将具有较低的值it.first
(因为相等的值不会添加新元素)。因为 astd::map
是一个排序容器(通常存储为二叉树),遍历 astd::map
将从最低元素开始并工作到最大元素。由于新元素小于 for 循环中的当前元素,因此新元素不会被当前循环处理(尽管它将用于外i
循环的下一次迭代)。
推荐阅读
- rust - 反向 Shell 中的 Rust 命令行历史
- javascript - 当我单击 Angular 组件中的按钮时无法更改 html 类
- python - 如何在标签中的 tkinter 中显示来自数据库的数据?
- javascript - 将 React 组件字符串转换为 JSX
- javascript - 如何软拷贝一个对象及其里面的所有函数?
- r - 使ggplot aes颜色映射以逻辑语句为条件
- javascript - 当我在我的 ionic 应用程序中从我的 Mapbox 地图中选择一条路线时,我无法让地图再次渲染
- python - 带有枚举的for循环中的计数器变量错误
- java - 无法将 Java getBytes() 转换为 php
- xml - 插入字符串变量作为新元素的属性值时遇到问题