这是一个可以使用动态规划解决的问题示例。以下有效的
Java代码可以在O(M * N^2)时间内解决此问题,其中
M = 城市数量,
N = 医院总数。
public void run(){
arr[0] = 100;
arr[1] = 100;
arr[2] = 200;
System.out.println(minCost(0, 4));
printBestAllocation(0, 4, minCost(0, 4));
}
static HashMap<String, Integer> map = new HashMap<String, Integer>();
static void printBestAllocation(int i, int n, int ans){
if(i>=arr.length){
return;
}
if(n<=0){
throw new RuntimeException();
}
int remainingCities = arr.length - i - 1;
for(int place=1; place<=n-remainingCities; place++){
if(arr[i] % place == 0){
int ppl = Math.max(arr[i] / place, minCost(i+1, n-place));
if(ppl == ans){
System.out.print(place + " ");
printBestAllocation(i+1, n-place, minCost(i+1, n-place));
return;
}
}else{
int ppl = Math.max(arr[i] / place + 1, minCost(i+1, n-place));
if(ppl==ans){
System.out.print(place + " ");
printBestAllocation(i+1, n-place, minCost(i+1, n-place));
return;
}
}
}
throw new RuntimeException("Buggy code. If this exception is raised");
}
static int minCost(int i, int n){
if(i>=arr.length){
return 0;
}
if(n<=0){
throw new RuntimeException();
}
String s = i + " " + n;
if(map.containsKey(s)){
return map.get(s);
}
int remainingCities = arr.length - i - 1;
int best = Integer.MAX_VALUE;
for(int place=1; place<=n-remainingCities; place++){
int ppl;
if(arr[i] % place==0){
ppl = Math.max(arr[i] / place, minCost(i+1, n-place));
}else{
ppl = Math.max(arr[i] / place + 1, minCost(i+1, n-place));
}
best = Math.min(best, ppl);
}
map.put(s, best);
return best;
}
州的表示形式为(i,n),其中i代表第i个城市,n代表可用医院数量。它表示任何从第i个城市开始到末尾分配n个医院的最大访问任何医院的人数。因此,对于您在问题中提到的示例,答案将是状态(0,4)。
因此,在每个城市,您可以最多放置n-remainingCities个医院,其中remainingCities = totalCities-i-1。因此,请从该城市至少放置1个医院,直到maxHospitals,并针对其他较小的子问题进行递归。
状态数= O(M * N^2),
每个状态的时间= O(1)
因此,时间复杂度= O(M * N^2)。