1,应用场景—集合覆盖问题
- 假设存在下面需要付费的广播电台,以及广播电台可以覆盖的地区。如何选择最少的电台,能实现区域的全覆盖
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6276957accda40e19ffdfe0aaeda4d26.png)
2,贪心算法介绍
- 贪心算法(贪婪算法)是指在对问题进行求解时,在每一步的选择中都选择最优解,从而期望能够导致结果是最优解的算法
- 贪心算法所得到的结果不一定是最优解,但是一定是相对近似最优解的结果
3,贪心算法最佳应用演示—集合覆盖问题
- 已知存在多少电台,及电台对应的覆盖城市集合;并且各个电台所覆盖城市存在部分重复,需要最少几部电台可实现全覆盖
- 首先汇总需要覆盖的城市,取各个电台对应城市的并集,作为汇总城市,并全部表示为未覆盖城市
- 然后遍历各个电台,统计各个电台在未覆盖的城市中可以覆盖几座城市
- 统计完成后,取覆盖城市最多的电台为最优解,即为先用电台,添加到选用集合;同时,从未覆盖城市集合中删除该电台覆盖的城市
- 再剩余未覆盖的城市中,重复第3和第4步,直到未覆盖城市数为0,即表示城市已经被全部覆盖
- 最终返回选用集合,表示最终选择的电台
- 注意:此处虽然在每一步取得了最优解,但是最终结果不一定是最优解,这也是贪心算法的特性
4,代码实现
package com.self.datastructure.algorithm.greed;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
public class Greed {
public static void main(String[] args) {
Map<String, Set<String>> redioMap = new HashMap<>(16);
redioMap.put("K1", new HashSet<>(Arrays.asList("北京", "上海", "天津")));
redioMap.put("K2", new HashSet<>(Arrays.asList("广州", "北京", "深圳")));
redioMap.put("K3", new HashSet<>(Arrays.asList("成都", "上海", "杭州")));
redioMap.put("K4", new HashSet<>(Arrays.asList("上海", "天津")));
redioMap.put("K5", new HashSet<>(Arrays.asList("杭州", "大连")));
System.out.println(greed(redioMap));
}
private static Set<String> greed(Map<String, Set<String>> redioMap) {
Set<String> lstTotalCities = getTotalCities(redioMap.values());
Set<String> lstRedio = new HashSet<>(10);
String maxKey = null;
int maxCount = 0;
for (;lstTotalCities.size() > 0;) {
maxKey = null;
maxCount = 0;
for (Map.Entry<String, Set<String>> entry : redioMap.entrySet()) {
Set<String> lstCities = entry.getValue();
int currCount = getRetainCount(lstTotalCities, lstCities);
if (currCount > 0 && currCount > maxCount) {
maxKey = entry.getKey();
maxCount = currCount;
}
}
if (StringUtils.isNotEmpty(maxKey)) {
lstRedio.add(maxKey);
lstTotalCities.removeAll(redioMap.get(maxKey));
}
}
return lstRedio;
}
private static int getRetainCount(Set<String> lstTotalCities, Set<String> lstCities) {
int count = 0;
for (String city : lstCities) {
if (lstTotalCities.contains(city)) {
count++;
}
}
return count;
}
private static Set<String> getTotalCities(Collection<Set<String>> values) {
Set<String> lstTotalCities = new HashSet<>(10);
for (Set<String> lstCurrData : values) {
lstTotalCities.addAll(lstCurrData);
}
return lstTotalCities;
}
}