遍历多映射以查找从给定值到给定关键字的路径
Traverse MultiMap to Find Path from a Given Value to a Given Key
详细信息:
我有一个多映射实现,它表示图的子集的邻接列表。
我需要找到一条通过图的这个子集的路径,它实际上是从开始节点F
到结束节点G
的所有可能的路径,通过对全图进行广度优先搜索来获得。
实施理念:
一旦找到G
,BFS就会退出,因此您最终只能在多映射的值中使用G
。我的想法是,如果你从值G
开始,得到G
的"键"(我们称之为H
(,如果H == F
,那么我们就有了我们的路径。否则,继续查找H
作为与另一个键关联的值(称之为D
(,如果是D == F
,则我们有自己的路径。。。在这一点上,我们从F
开始的路径看起来像F -> H -> G
问题:
这个规模会吗?由于映射只包含从F
到G
的可能路径的子集,在G处停止,因此它不应该意外地生成循环路径或生成重复密钥。如果子集的基数为n,那么n将是任何给定密钥的最大值,因此连接的边的数量永远不会超过n。
您将如何对此进行编码
我能思考其中的逻辑和数学问题,但我对地图库的理解还不够好,还不能自己写出来在阅读c++参考后,我想到我可以使用映射方法upper/lowerbound
,但我找不到支持这一点的示例
结果是相对琐碎的:
typedef multimap<int, int> MapType;
typedef MapType::const_iterator MapItr;
vector<int> path;
path.push_back(G);
int end = G; // we know G, so mark it
while ( end != F ) { // as long as mark is not F
// now loop through map searching for value that matches G
for (MapItr iter = pathMap.begin(); iter != pathMap.end(); iter++)
{
if (iter->second == end) { // once we find our marked value/vertex
path.push_back(iter->first); // push it's key onto the vector
end = iter->first; // and mark it's key for next iteration
// continue this until end reaches F
} // at which point will have our path
// from G to F
}
}
// avoid this step by using a container with a push_front method
reverse(path.begin(), path.end()); // reverse path
您可以作为循环浏览整个地图
C++11
for(const auto& key_val: the_map)
{
std::cout<<key_val.first<<":"<<key_val.second<<std::endl;
}
非C++11
for(the_map_type::const_iterator itr = the_map.begin(); itr != the_map.end();++itr)
{
std::cout<<itr->first<<":"<<itr->second<<std::endl;
}
the_map.lower_bound(key)
将为具有关键字key
的第一个元素提供迭代器
the_map.upper_bound(key)
将为元素提供一个迭代器,该迭代器位于键为key
的任何元素之后
相关文章:
- Visual Studio 2015:Extern "C" 和 "export" 关键字
- C++中的"inline"关键字
- 如何确保C++函数在定义之前声明(如override关键字)
- 如何将更多文件夹添加到c++include路径
- 带有特殊路径部分的"std::filesystem::weakly_canonical"失败
- C++A*算法并不总是在路径中具有目标节点
- 从函数角度看ID到文件路径的内部与外部映射
- boost xml parsingl将xml的路径作为变量发送
- 谷歌模拟和覆盖关键字
- 对于MacOS上的G++,如何添加默认的include目录/usr/local/include和默认的库搜索路径/usr
- 如何使用cppcheck处理半相对包含路径
- 在C++中设置基于操作系统的文件路径
- 基于编译器选项的编译二进制路径
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 按边长度递归搜索图中所有可行路径
- 使用变量值作为 PlaySound 中的路径
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- 如何转换真实路径 CString c++
- 遍历多映射以查找从给定值到给定关键字的路径