import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet;
public class 贪心算法 { public static void main(String[] args) { HashMap<String, HashSet<String>> broadcasts =new HashMap<String,HashSet<String>>(); HashSet<String> hashSet1 = new HashSet<String>(); hashSet1.add("北京"); hashSet1.add("上海"); hashSet1.add("天津");
HashSet<String> hashSet2 = new HashSet<String>(); hashSet1.add("广州"); hashSet1.add("北京"); hashSet1.add("深圳"); HashSet<String> hashSet3 = new HashSet<String>(); hashSet1.add("成都"); hashSet1.add("上海"); hashSet1.add("杭州"); HashSet<String> hashSet4 = new HashSet<String>(); hashSet1.add("上海"); hashSet1.add("天津"); HashSet<String> hashSet5 = new HashSet<String>(); hashSet1.add("杭州"); hashSet1.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<String>(); hashSet1.add("北京"); hashSet1.add("上海"); hashSet1.add("天津"); hashSet1.add("广州"); hashSet1.add("深圳"); hashSet1.add("成都"); hashSet1.add("杭州"); hashSet1.add("大连");
ArrayList<String> selects = new ArrayList<String>();
HashSet<String> tempSet = new HashSet<String>();
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.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.toString());
} }
|