向量之间的交集

Intersection between vectors

本文关键字:之间 向量      更新时间:2023-10-16

我有以下形式的数据。

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|)上面的解决方案。