public class 分治算法 {
public static void main(String[] args) {
merge(3, 'a', 'b', 'c');
System.out.println("共需要移动" + count + "次");
}
static int count = 0;
public static void merge(int n, char a, char b, char c) {
if (n == 1) {
System.out.println("第1个盘:a->c");
count++;
} else {
//看成两个盘,最下面的盘和上面的盘
merge(n - 1, a, c, b);//把上面的盘a->b,以c作为中转
System.out.println("第" + n + "个盘:a->c");//把最下面的盘a->c
count++;
merge(n - 1, b, a, c);//把上面的盘b->c,以a作为中转
}
}
}
public class 贪心算法 {
public static void main(String[] args) {
HashMap<String, ArrayList<String>> hashMap = new HashMap<>();
ArrayList<String> k1 = new ArrayList<>();
k1.add("北京");
k1.add("上海");
k1.add("天津");
hashMap.put("k1", k1);
ArrayList<String> k2 = new ArrayList<>();
k2.add("广州");
k2.add("深圳");
k2.add("北京");
hashMap.put("k2", k2);
ArrayList<String> k3 = new ArrayList<>();
k3.add("成都");
k3.add("上海");
k3.add("杭州");
hashMap.put("k3", k3);
ArrayList<String> k4 = new ArrayList<>();
k4.add("上海");
k4.add("天津");
hashMap.put("k4", k4);
ArrayList<String> k5 = new ArrayList<>();
k5.add("杭州");
k5.add("大连");
hashMap.put("k5", k5);
minCount(hashMap);
}
public static void minCount(HashMap<String, ArrayList<String>> video) {
//所有城市的集合
HashSet<String> allCities = new HashSet<>();
for (String key : video.keySet()) {
for (String s : video.get(key)) {
allCities.add(s);
}
}
int cityNumber = allCities.size();//保留所有城市的个数
HashMap<String, Integer> videoCount = new HashMap<>(); //每个电台覆盖的有效城市个数
ArrayList<String> getVideo = new ArrayList<>();//存放取出的电台
Set<String> getCity = new HashSet<>();//存放已覆盖的城市
while (getCity.size() < cityNumber) {//城市没有被完全覆盖
//统计每个电台覆盖的有效城市个数
cityNumber(video, allCities, videoCount);
//找到覆盖的城市最多的电台
int min = 0;
String key = "";
for (String s : videoCount.keySet()) {
if (videoCount.get(s) > min) {
min = videoCount.get(s);
key = s;
}
}
//把这个电台添加到集合中
getVideo.add(key);
//把这个电台覆盖的城市添加到已覆盖城市中
for (String s : video.get(key)) {
getCity.add(s);
}
//把这个电台覆盖的城市从城市集合中移除
for (String s : video.get(key)) {
if (allCities.contains(s)) {
allCities.remove(s);
}
}
//把这个电台从电台集合中移除
video.remove(key);
//把这个电台从统计有效个数的集合中移除
videoCount.remove(key);
}
System.out.println(getVideo);
}
//统计每个电台覆盖的城市个数
public static void cityNumber(
HashMap<String, ArrayList<String>> video, HashSet<String> allCities, HashMap<String, Integer> videoCount) {
for (String s : video.keySet()) {//video的键,遍历所有的电台
int count = 0;
for (String ss : video.get(s)) {//每个电台覆盖的城市
if (allCities.contains(ss)){
count++;
}
}
videoCount.put(s, count);
}
}
}