矢量之间的交叉点

时间:2016-02-20 18:03:21

标签: c++ c++11

我有以下表格的数据。

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);
}
}

1 个答案:

答案 0 :(得分:2)

(2,2)代表10??,我们不关心??是什么。这是半开放范围10001100,又名[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 |)。