向量之间的交集
Intersection between vectors
我有以下形式的数据。
vector<pair<unsigned,unsigned> > vecA; //here first value denotes reolution and second value denotes value. All values are of 4 bits
vecA.push_back(make_pair(2,2)); vecA.push_back(make_pair(2,3)); vecA.push_back(make_pair(3,6)); vecA.push_back(make_pair(3,7)); vecA.push_back(make_pair(4,5));
(2,2)-> signifies that the first 2 bits of value(a 4 bit number) are 10. i.e. the value could be "1000,1001,1010,1011" in binary
(2,3)-> signifies that the first 2 bits of value(a 4 bit number) are 11 i.e. the value could be "1100,1101,1110, 1011" in binary
(3,6)-> signifies that the first 3 bits of value(a 4 bit number) are 110 i.e., the value could be "1100,1101" in binary
(3,7)-> signifies that the first 3 bits of value(a 4 bit number) are 111 i.e., the value could be "1110,1111" in binary
(4,5)-> signifies that the first 4 bits of value(a 4 bit number) are 0101 i.e., the value is "0101" in binary
我有另一个包含以下内容的向量:
vector<unsigned> vecB; //vecB has a by default resolution of 4. Here too the values are of 4 bits
vecB.push_back(10); vecB.push_back(6); vecB.push_back(13); vecB.push_back(12); vecB.push_back(15); vecB.push_back(5); vecB.push_back(7);
10-> signifies that the 4 bit number is: "1010"
6-> signifies that the 4 bit number is: "0110"
13-> signifies that the 4 bit number is: "1101"
12-> signifies that the 4 bit number is: "1100"
15-> signifies that the 4 bit number is: "1111", etc.
现在,vecA 和 vecB 之间的交集应该执行位级比较,即对于 vecA 的 2 位分辨率,只应该看到 vecB 的前两位。
i.e. (2,2) of vecA matches with "10" of vecB
(2,3) of vecA matches with "13,12,15" of vecB
(3,6) of vecA matches with "12,13" of vecB
(3,7) of vecA matches with "15" of vecB
(4,5) matches with "5" of vecB
交集应仅返回来自 vecB 的匹配值,即交集应返回"10,13,12,15,5"作为结果。
如何在 c++ 中有效地执行此交集?
vector<unsigned> ans;
for(vector<pair<unsigned,unsigned> >::iterator i1=vecA.begin(), l1=vecA.end(); i1!=l1;++i1)
{
for(vector<unsigned>::iterator i2=vecB.begin(),l2=vecB.end();i2!=l2;++i2)
{
if(((*i2)>>(*i1).first)==(*i1).second)
ans.push_back((*i1).second);
}
}
(2,2)
代表10??
,我们不在乎??
是什么。 这是通过1100
1000
的半开放范围,又名[2 << 2, (2+1)<<2)
。
因此,从 LHS 生成一组范围。 任何重叠的东西,引信。 您将有一组开始/结束间隔。
现在对 RHS 进行排序。 接下来,遍历它,跟踪您何时进入/退出 LHS 间隔。 那些在 LHS 区间中的位于交叉点。
RHS 排序需要 O(|RHS|LG |RHS|)。 步行需要O(|RHS|+ |LHS|)。
建立 LHS 间隔需要 O(|LHS|LG |LHS|)时间(包括按间隔开始排序的时间)。 合并它们是一次传递,也是 O(|LHS|)。
所以最终结果是 O(|RHS|LG |RHS|+ |LHS|LG |LHS|)计算交集的时间,而不是 O(|RHS|* |LHS|)上面的解决方案。
相关文章:
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 在C++中查找两个向量之间最相似的值
- C++在 2 个向量向量之间交换向量
- p_threads初始化中向量和数组之间的区别
- 查找多个向量之间的公共元素(无整数元素)
- 在两个类实例之间共享向量
- C++向量:clear() 和 resize() 之间的区别
- 由 std::shared_ptr 向量指向的数据之间的线程同步
- C++ std::vector 创建对象然后添加对象与在向量中创建对象之间的区别?
- C 计算两个3D向量之间的角度(0至360)
- 在C 中,是否有可能在不兼容类型的std ::向量对象之间传输不同类型的缓冲区
- C++:快速/并行计算两个"std::vector<double>"向量之间的L1距离
- 计算三个或更多向量之间的向量
- 如何在C++中找到两个向量之间的最小(优化)距离
- 列表和向量的索引之间的差异
- 如何在指定数据之间将数据从一个向量获取到另一个向量
- 编译器如何在向量vs Initializer_list之间做出决定
- 字符串和向量<string>元素之间的区别
- 在两个std::向量之间匹配元素
- 用整数密钥和向量的地图之间的差异