2025-01-25 贪心算法-电台问题

This commit is contained in:
liangjinglin 2025-01-31 16:47:55 +08:00
parent d11a8f629c
commit 7897698f68

View File

@ -0,0 +1,83 @@
package algorithm;
import java.util.*;
public class Greedy {
private HashMap<String, List<String>> radios = new HashMap<>();
private HashSet<String> areas = new HashSet<>();
private List<String> selectRadios = new ArrayList<>();
private void allArea(){
for(Map.Entry<String, List<String>> entry : radios.entrySet()){
areas.addAll(entry.getValue());
}
}
private void greedySelectRadio(){
while(areas.size() > 0){
String maxKey = "";
int coverSize = 0;
for(Map.Entry<String, List<String>> entry : radios.entrySet()){
int currentCoverSize = 0;
List<String> values = entry.getValue();
for(String value : values){
if(areas.contains(value)){
currentCoverSize ++;
}
}
if(currentCoverSize > coverSize){
maxKey = entry.getKey();
coverSize = currentCoverSize;
}
}
selectRadios.add(maxKey);
List<String> selects = radios.get(maxKey);
for(String select : selects){
areas.remove(select);
}
}
}
private void showSelectRadio(){
System.out.println("选择的电台:");
for(String radio : selectRadios){
System.out.println(radio);
}
}
public static void main(String[] args) {
Greedy greedy = new Greedy();
List<String> K1 = new ArrayList<>();
K1.add("北京");
K1.add("上海");
K1.add("天津");
greedy.radios.put("K1", K1);
List<String> K2 = new ArrayList<>();
K2.add("北京");
K2.add("广州");
K2.add("深圳");
greedy.radios.put("K2", K2);
List<String> K3 = new ArrayList<>();
K3.add("成都");
K3.add("上海");
K3.add("杭州");
greedy.radios.put("K3", K3);
List<String> K4 = new ArrayList<>();
K4.add("上海");
K4.add("天津");
greedy.radios.put("K4", K4);
List<String> K5 = new ArrayList<>();
K5.add("杭州");
K5.add("大连");
greedy.radios.put("K5", K5);
greedy.allArea();
greedy.greedySelectRadio();
greedy.showSelectRadio();
}
}