贪心算法(电台覆盖问题实现)
贪心算法
(1)贪婪算法(贪心算法)是指在对问题进行求解时,在每一步选择中都采取最好或者最优(即最有利)的选择,从而希望能够导致结果是最好或者最优的算法
(2)贪婪算法所得到的结果不一定是最优的结果(有时候会是最优解),但是都是相对近似(接近)最优解的结果
贪心算法问题:电台覆盖问题
贪心算法求解思路
第一步: 第二步: 第三步: 第四步: 第五步:
java代码实现
package com
.bingym
.greedy
;
import java
.util
.*
;
public class GreedyAlgorithm {
public static void main(String
[] args
) {
HashMap
<String
, HashSet
<String>> broadcasts
= new HashMap<String
, HashSet
<String>>();
HashSet
<String> broadcast1
= new HashSet<String>();
broadcast1
.add("北京");
broadcast1
.add("上海");
broadcast1
.add("天津");
HashSet
<String> broadcast2
= new HashSet<String>();
broadcast2
.add("广州");
broadcast2
.add("北京");
broadcast2
.add("深圳");
HashSet
<String> broadcast3
= new HashSet<String>();
broadcast3
.add("成都");
broadcast3
.add("上海");
broadcast3
.add("杭州");
HashSet
<String> broadcast4
= new HashSet<String>();
broadcast4
.add("上海");
broadcast4
.add("天津");
HashSet
<String> broadcast5
= new HashSet<String>();
broadcast5
.add("杭州");
broadcast5
.add("大连");
broadcasts
.put("K1", broadcast1
);
broadcasts
.put("K2", broadcast2
);
broadcasts
.put("K3", broadcast3
);
broadcasts
.put("K4", broadcast4
);
broadcasts
.put("K5", broadcast5
);
HashSet
<String> allAreas
= new HashSet<String>();
for (Map
.Entry
<String
, HashSet
<String>> entry
: broadcasts
.entrySet()) {
for (String s
: entry
.getValue()) {
allAreas
.add(s
);
}
}
List
<String> selects
= new ArrayList<>();
HashSet
<String> tempSet
= new HashSet<>();
String maxKey
= null
;
while (allAreas
.size() != 0) {
maxKey
= null
;
for (String key
: broadcasts
.keySet()) {
tempSet
.clear();
HashSet
<String> ares
= broadcasts
.get(key
);
tempSet
.addAll(ares
);
tempSet
.retainAll(allAreas
);
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
);
}
}
最后输出结果
:
最优的电台选择策略为
:[K1
, K2
, K3
, K5
]