遍历多映射以查找从给定值到给定关键字的路径

Traverse MultiMap to Find Path from a Given Value to a Given Key

本文关键字:关键字 路径 查找 遍历 映射      更新时间:2023-10-16

详细信息:

我有一个多映射实现,它表示图的子集的邻接列表。

我需要找到一条通过图的这个子集的路径,它实际上是从开始节点F到结束节点G的所有可能的路径,通过对全图进行广度优先搜索来获得。

实施理念:

一旦找到G,BFS就会退出,因此您最终只能在多映射的值中使用G。我的想法是,如果你从值G开始,得到G的"键"(我们称之为H(,如果H == F,那么我们就有了我们的路径。否则,继续查找H作为与另一个键关联的值(称之为D(,如果是D == F,则我们有自己的路径。。。在这一点上,我们从F开始的路径看起来像F -> H -> G

问题:

这个规模会吗?由于映射只包含从FG的可能路径的子集,在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的任何元素之后