【发布时间】:2018-08-01 01:35:55
【问题描述】:
我有许多 0 和 1 的序列,我想找到具有最大数量的其他序列的序列,这些序列构成当前序列的前缀。
例子:
std::vector<std::vector<int>> sequence={{1,1},{1},{0,1,0,1},{1,1,0}}
{1,1} 只有 1 个前缀,即 {1}。
但是 {1,1,0} 有 2 个前缀 {1,1} 和 {1}。由于它具有最多的前缀计数,我想选择sequence. 的索引 3 我可以使用嵌套循环来完成它,但它会消耗大量时间,因为我必须处理大小为 512 的序列。感谢您的帮助。
到目前为止我做了什么:
bool isPrefixOf(std::vector<int> current, std::vector<int> other){
if (other.size()>current.size())
return false;
for (int i=0; i<other.size(); ++i) {
if (other[i] != current[i])
return false;
}
return true;
}
int len = sequence.size();
int max = 0;
int selected = -1;
int prefix_count;
for(int i=0; i<len; i++){
prefix_count = 0;
for(int j=0; j<len; j++){
if(isPrefixOf(sequence[i],sequence[j])) ++prefix_count;
}
if(prefix_count >= max){
max = prefix_count;
selected = i;
}
}
【问题讨论】:
-
你会有
selected = i;,我。 e. index 您找到最大值的位置。 -
@Aconcagua 啊,真的。
-
抱歉,一直没注意(这里是凌晨四点……)。
标签: c++ algorithm stdvector prefix