贪心算法实现从电台的问题

谁借莪1个温暖的怀抱¢ 2022-12-01 15:38 168阅读 0赞
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <set>
  4. #include <string>
  5. #include <iterator>
  6. #include <vector>
  7. #include <map>
  8. #include <functional>
  9. using namespace std;
  10. int main09()
  11. {
  12. map<string, set<string>> broadcast;
  13. set<string> Set1;
  14. Set1.insert("北京");
  15. Set1.insert("上海");
  16. Set1.insert("天津");
  17. set<string> Set2;
  18. Set2.insert("北京");
  19. Set2.insert("广州");
  20. Set2.insert("深圳");
  21. set<string> Set3;
  22. Set3.insert("成都");
  23. Set3.insert("上海");
  24. Set3.insert("杭州");
  25. set<string> Set4;
  26. Set4.insert("上海");
  27. Set4.insert("天津");
  28. set<string> Set5;
  29. Set5.insert("杭州");
  30. Set5.insert("大连");
  31. broadcast.insert(pair<string, set<string>>("K1", Set1));
  32. broadcast.insert(pair<string, set<string>>("K2", Set2));
  33. broadcast.insert(pair<string, set<string>>("K3", Set3));
  34. broadcast.insert(pair<string, set<string>>("K4", Set4));
  35. broadcast.insert(pair<string, set<string>>("K5", Set5));
  36. set<string> allAreas;
  37. allAreas.insert("北京");
  38. allAreas.insert("上海");
  39. allAreas.insert("广州");
  40. allAreas.insert("天津");
  41. allAreas.insert("深圳");
  42. allAreas.insert("成都");
  43. allAreas.insert("杭州");
  44. allAreas.insert("大连");
  45. vector<string> selects;
  46. //定义一个临时的集合来存放该电台和未地区之间的交集
  47. set<string> tmpSet;
  48. string maxKey = "";
  49. int num = 0;
  50. while (allAreas.size() > 0) {
  51. for (auto &bbb : broadcast)
  52. {
  53. set<string> areas = bbb.second;
  54. set_intersection(allAreas.begin(), allAreas.end(), areas.begin(), areas.end(), \
  55. inserter(tmpSet, tmpSet.begin()));
  56. if (tmpSet.size() > 0 && (maxKey == "" || tmpSet.size() > num))
  57. {
  58. maxKey = bbb.first;
  59. num = tmpSet.size();
  60. }
  61. tmpSet.clear();
  62. }
  63. selects.push_back(maxKey);
  64. auto iter = broadcast.find(maxKey);
  65. if (iter != broadcast.end())
  66. {
  67. set<string> tmpSet1;
  68. set_difference(allAreas.begin(), allAreas.end(), iter->second.begin(), \
  69. iter->second.end(), inserter(tmpSet1, tmpSet1.begin()));
  70. allAreas = tmpSet1;
  71. broadcast.erase(iter);
  72. }
  73. maxKey = "";
  74. num = 0;
  75. }
  76. vector<int> itsMy{ 1,2,4,5,6,10 };
  77. cout << count_if(itsMy.begin(), itsMy.end(), not1(bind2nd(less<int>(), 10))) << endl;
  78. copy(selects.begin(), selects.end(), ostream_iterator<string>(cout, ","));
  79. not1(bind2nd(less<int>(), 10))(5);
  80. return 0;
  81. }

发表评论

表情:
评论列表 (有 0 条评论,168人围观)

还没有评论,来说两句吧...

相关阅读

    相关 java实现贪心算法

    一、应用场景-集合覆盖问题 假设存在下面需要付费的广播台,以及广播台信号可以覆盖的地区。 如何选择最少的广播台,让所有的地区 都可以接收到信号 ![在这里插入图片描述

    相关 python实现贪心算法

    > 贪心算法是指在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,它所做出的是在某种意义上的局部最优解。 1. 贪心算法思想 贪心算法的基

    相关 零开始学贪心算法

    贪心算法的定义: 贪心算法是指在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,只做出在某种意义上的局部最优解。贪心算法不是对所有问题都能得