贪心算法所得到的结果不一定是最优解(有时候会是最优解),但是都是相对(接近)最优解的结果。
代码:
package Algorithm.greedy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class GreedyAlgorithm {
public static void main(String[] args) {
//创建广播电台
HashMap<String, HashSet<String>> broadcasts = new HashMap<String,HashSet<String>>();
//将各个电台放入broadcasts
HashSet<String> hashSet1 = new HashSet<>();
hashSet1.add("北京");
hashSet1.add("上海");
hashSet1.add("天津");
HashSet<String> hashSet2 = new HashSet<>();
hashSet2.add("广州");
hashSet2.add("北京");
hashSet2.add("深圳");
HashSet<String> hashSet3 = new HashSet<>();
hashSet3.add("成都");
hashSet3.add("上海");
hashSet3.add("杭州");
HashSet<String> hashSet4 = new HashSet<>();
hashSet4.add("上海");
hashSet4.add("天津");
HashSet<String> hashSet5 = new HashSet<>();
hashSet5.add("杭州");
hashSet5.add("大连");
broadcasts.put("K1",hashSet1);
broadcasts.put("K2",hashSet2);
broadcasts.put("K3",hashSet3);
broadcasts.put("K4",hashSet4);
broadcasts.put("K5",hashSet5);
HashSet<String> allAreas = new HashSet<>();
for (String city: hashSet1){
allAreas.add(city);
}
for (String city: hashSet2){
allAreas.add(city);
}
for (String city: hashSet3){
allAreas.add(city);
}
for (String city: hashSet4){
allAreas.add(city);
}
for (String city: hashSet5){
allAreas.add(city);
}
for (String city: allAreas) {
System.out.println(city);
}
//创建ArrayList,存放选择的电台集合
ArrayList<String> selects = new ArrayList<>();
//定义一个临时的集合,存放遍历过程中电台覆盖的地区和当前还没有覆盖地区的交集
HashSet<String> tempSet = new HashSet<>();
//定义maxKey,保存在一次遍历过程中,能够覆盖最大未覆盖地区对应的电台的key
String maxKey = null;
while ( allAreas.size() != 0 ){
maxKey = null;
for (String key: broadcasts.keySet()){
tempSet.clear();
//获取当前电台能覆盖的地区
HashSet<String> areas = broadcasts.get(key);
tempSet.addAll(areas);
//求tempSet 和 allAreas 的交集,并赋给tempSet
tempSet.retainAll(allAreas);
//如果当前这个集合包含的未覆盖地区的数量,比maxKey指向的集合地区还多,则重置maxKey
if (tempSet.size() > 0 && (maxKey == null || tempSet.size() > broadcasts.get(maxKey).size())) {
maxKey = key;
}
}
if (maxKey != null) {
selects.add(maxKey);
allAreas.removeAll(broadcasts.get(maxKey));
}
}
System.out.println("选择的结果为:"+selects);
}
}