java资源分配算法_java - 资源分配与动态规划算法 - 堆栈内存溢出

本文探讨了一种Java实现的资源分配算法,目标是在有限时间内最大化多个函数的输出总和。算法通过比较不同函数在特定时间点的输出,并结合前一状态的最大值,动态调整时间分配以达到最优解。然而,示例代码存在一个问题,导致最大输出为30,而不是预期的31。
摘要由CSDN通过智能技术生成

给定一组函数f1 ... fn(离散时间)和时间限制(int),应找到最大输出,即在不同函数之间分配时间以最大化所用函数输出的总和。

对于任何函数,任何时候的值表示如果用于所述时间的函数的总输出。 即F(2)=函数的总输出,如果使用2秒。 不是F(1)+ F(2)。

所有值(时间,函数输出)都是整数。

我的当前算法通过检查F(t)找到所有时间被放入一个函数的情况,将最大值与前一个最大M(t-1)+的所有可能输出的最大值进行比较,找出可能损坏的最大值为每个可能的功能添加1秒(带有已使用功能和时间的记录)。

public int computeDamage(){

int totalTime = calculator.getTotalTime();

int numAttacks = calculator.getNumAttacks();

if(totalTime == 0) return 0;

int[] attackHist = new int[numAttacks];

return maxDamage(numAttacks, attackHist, 1, totalTime, 0);

}

public int maxDamage(int numAttacks, int[] attackHist, int start, int end, int max) {

//get the max of all the values at f(start), save the attack

int maxF = -1, attack = -1;

for(int i = 0; i < numAttacks; i++) {

int dam = calculator.calculateDamage(i, start);

if(dam > maxF) {

maxF = dam;

attack = i;

}

}

//if start isn't 1, get the max of all possible values added to the attackHist

int maxH = -1, attackH = -1;

if(start > 1) {

for(int j = 0; j < numAttacks; j++) {

int dChange = -1;

if(attackHist[j] > 0) dChange = calculator.calculateDamage(j, attackHist[j]+1) - calculator.calculateDamage(j, attackHist[j]);

else dChange = calculator.calculateDamage(j, attackHist[j]+1);

if((max + dChange) > maxH) {

maxH = max + dChange;

attackH = j;

}

}

//if max is greater, reset attackHist. Otherwise, add 1 to used attack

if(maxF > maxH) {

Arrays.fill(attackHist, 0);

attackHist[attack] = start;

max = maxF;

} else {

attackHist[attackH]++;

max = maxH;

}

} else {

//just set the max to maxF

max = maxF;

attackHist[attack] = 1;

}

if(end == start) return max;

else return maxDamage(numAttacks, attackHist, start+1, end, max);

}

输入12.in

20 12

0 3 4 7 9 12 12 14 15 15 17 19

2 5 6 9 11 12 15 15 16 19 21 22

1 4 6 8 9 11 13 14 16 18 21 22

1 4 4 4 5 5 6 8 9 11 12 14

0 3 4 5 7 10 12 13 15 17 20 20

1 3 5 5 8 10 10 12 14 15 16 18

1 1 3 5 7 8 10 11 11 13 14 16

1 1 2 2 2 3 6 7 10 11 11 12

1 3 5 5 7 7 8 11 11 12 14 16

0 1 4 5 6 9 10 11 12 12 15 18

3 5 5 7 8 10 12 12 14 15 15 16

3 5 6 9 12 12 13 14 15 18 21 21

1 2 3 4 7 9 10 12 12 15 18 18

3 4 5 7 8 10 12 13 13 16 17 20

3 5 7 7 10 11 14 16 17 18 21 23

0 1 4 7 7 8 10 12 13 13 14 16

2 3 3 6 8 9 12 15 17 18 20 21

0 2 3 3 6 8 9 10 13 15 17 17

1 2 4 7 9 9 9 11 14 14 17 19

3 5 6 7 10 11 12 12 13 16 17 19

第一行告诉我们有多少函数(20)和多少时间(12秒)来最大化输出。

每一行都是一个定义为1到12 F(t)的函数,详细说明了该函数在该点之前完成了多少损坏。

输出应为31,但我的代码输出为30。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值