贪心算法

本文最后更新于:2022年12月13日 晚上

贪心算法

应用场景

集合覆盖

假设存在如下表的需要付费的广播台,以及广播台信号可以覆盖的地区。如何选择最少的广播台,让所有的地区都可以接收到信号

广播台 覆盖地区
K1 “北京”,”上海”,”天津”
K2 “广州”,”北京”,”深圳”
K3 “成都”,”上海”,”杭州”
K4 “上海”,”天津”
K5 “杭州”,”大连”

基本介绍

(1)贪婪算法(贪心算法)是指在对问题进行求解时,在每一步选择中都采取最好或者最优(即最有利)的选择,从而希望能够导致结果是最好或者最优的算法。

(2)贪心算法所得到的结果不一定是最优的结果(有时候会是最优解),但是都是相对近似(接近)最优解的结果

应用实现

上面的集合覆盖问题使用贪婪算法,效率高。

目前并没有算法可以快速计算得到准备的值,使用贪婪算法,则可以得到非常接近的解,并且效率高。选择策略上,因为需要覆盖全部地区的最小集合:

(1)遍历所有的广播电台,找到一个覆盖了最多未覆盖的地区的电台(此电台可能包含一些已覆盖的地区,但没有关系)。

(2)将这个电台加入到一个集合中(比如ArrayList),想办法把该电台覆盖的地区在下次比较时去掉。

(3)重复第1步直到覆盖了全部的地区。

代码实现

// 贪心算法解决集合覆盖问题
public class GreedyAlgorithm {
    public static void main(String[] args) {
        HashMap<String, HashSet<String>> map = new HashMap<>();
        HashSet<String> hashSet1 = new HashSet<>();
        hashSet1.add("BJ");
        hashSet1.add("SH");
        hashSet1.add("TJ");
        HashSet<String> hashSet2 = new HashSet<>();
        hashSet2.add("GZ");
        hashSet2.add("BJ");
        hashSet2.add("SZ");
        HashSet<String> hashSet3 = new HashSet<>();
        hashSet3.add("CD");
        hashSet3.add("SH");
        hashSet3.add("HZ");
        HashSet<String> hashSet4 = new HashSet<>();
        hashSet4.add("SH");
        hashSet4.add("TJ");
        HashSet<String> hashSet5 = new HashSet<>();
        hashSet5.add("HZ");
        hashSet5.add("DL");
        map.put("K1", hashSet1);
        map.put("K2", hashSet2);
        map.put("K3", hashSet3);
        map.put("K4", hashSet4);
        map.put("K5", hashSet5);

        HashSet<String> all = new HashSet<>();
        all.add("BJ");
        all.add("SH");
        all.add("TJ");
        all.add("GZ");
        all.add("SZ");
        all.add("CD");
        all.add("HZ");
        all.add("DL");

        ArrayList<String> selected = new ArrayList<>();
        HashSet<String> tempSet = new HashSet<>();
        String maxKey;
        while (all.size() != 0) {
            maxKey = null;
            for (String key : map.keySet()) {
                tempSet.clear();
                HashSet<String> areas = map.get(key);
                tempSet.addAll(areas);
                // 求出交集,交集会赋值给tempSet
                tempSet.retainAll(all);
                if (tempSet.size() > 0 && (maxKey == null || tempSet.size() > map.get(maxKey).size())) {
                    maxKey = key;
                }
            }
            if (maxKey != null) {
                selected.add(maxKey);
                all.removeAll(map.get(maxKey));
            }
        }
        System.out.println(selected);
    }
}

贪心算法
http://yorick.love/2022/08/10/算法/算法_贪心算法/
作者
Yorick
发布于
2022年8月10日
许可协议