Guest User

Untitled

a guest
Oct 22nd, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. #include <string>
  2. #include <unordered_map>
  3.  
  4. template<class T, class U> using umap = std::unordered_map<T, U>;
  5.  
  6.  
  7. umap<std::string, double> getWeights(const std::string& nodeName, const umap<std::string, umap<std::string, double>>& weightTrees)
  8. {
  9. const auto it = weightTrees.find(nodeName);
  10. if (it == weightTrees.end())
  11. return umap<std::string, double>();
  12.  
  13. umap<std::string, double> topWeights = it->second;
  14. std::vector<std::string> topNodeNames;
  15.  
  16. for (const auto& kv : topWeights)
  17. topNodeNames.push_back(kv.first);
  18.  
  19. for (const std::string& topNodeName : topNodeNames)
  20. {
  21. umap<std::string, double> subWeights = getWeights(topNodeName, weightTrees);
  22. if (subWeights.size() > 0)
  23. {
  24. const double topWeight = topWeights[topNodeName];
  25. topWeights.erase(topNodeName);
  26. for (const auto& subWeight : subWeights)
  27. {
  28. const auto it = topWeights.find(subWeight.first);
  29. if (it == topWeights.end())
  30. topWeights[subWeight.first] = topWeight * subWeight.second;
  31. else
  32. it->second += topWeight * subWeight.second;
  33. }
  34. }
  35. }
  36.  
  37. return topWeights;
  38. }
  39.  
  40.  
  41. int main()
  42. {
  43. umap<std::string, umap<std::string, double>> weightTrees = {{ "Node0", {{ "Node1",0.5 },{ "Node2",0.3 },{ "Node3",0.2 }} },
  44. { "Node1", {{ "Node2",0.1 },{ "Node4",0.9 }} }};
  45.  
  46. umap<std::string, double> w = getWeights("Node0", weightTrees); // gives {Node2: 0.35, Node3: 0.20, Node4: 0.45}
  47. }
Add Comment
Please, Sign In to add comment