如何解决无法理解区域DP的选择
考虑一个游戏,其中你有两种类型的权力,A 和 B,有 3 种类型的区域 X、Y 和 Z。每一秒你必须在这些区域之间切换,每个区域都有特定的属性,你的功率 A 和功率 B 增加或减少。我们需要不断选择区域,以使我们的生存时间最大化。当任何幂,A 或 B 达到小于 0 时,生存时间结束。 示例:
Initial value of Power A = 20
Initial value of Power B = 8
Area X (3,2) : If you step into Area X,A increases by 3,B increases by 2
Area Y (-5,-10) : If you step into Area Y,A decreases by 5,B decreases by 10
Area Z (-20,5) : If you step into Area Z,A decreases by 20,B increases by 5
It is possible to choose any area in our first step.
We can survive at max 5 unit of time by following
these choice of areas :
X -> Z -> X -> Y -> X
解决方法
这个问题可以用递归来解决,在每个时间单元之后我们可以去任何一个区域,但我们会选择最终导致最大生存时间的区域。由于递归会导致多次求解相同的子问题,我们将根据 A 和 B 的幂记忆结果,如果我们达到同一对 A 和 B 的幂,我们将不再求解,而是采用先前计算的结果。 下面给出了上述方法的简单实现。
// C++ code to get maximum survival time
#include <bits/stdc++.h>
using namespace std;
// structure to represent an area
struct area
{
// increment or decrement in A and B
int a,b;
area(int a,int b) : a(a),b(b)
{}
};
// Utility method to get maximum of 3 integers
int max(int a,int b,int c)
{
return max(a,max(b,c));
}
// Utility method to get maximum survival time
int maxSurvival(int A,int B,area X,area Y,area Z,int last,map<pair<int,int>,int>& memo)
{
// if any of A or B is less than 0,return 0
if (A <= 0 || B <= 0)
return 0;
pair<int,int> cur = make_pair(A,B);
// if already calculated,return calculated value
if (memo.find(cur) != memo.end())
return memo[cur];
int temp;
// step to areas on basis of last chose area
switch(last)
{
case 1:
temp = 1 + max(maxSurvival(A + Y.a,B + Y.b,X,Y,Z,2,memo),maxSurvival(A + Z.a,B + Z.b,3,memo));
break;
case 2:
temp = 1 + max(maxSurvival(A + X.a,B + X.b,1,memo));
break;
case 3:
temp = 1 + max(maxSurvival(A + X.a,maxSurvival(A + Y.a,memo));
break;
}
// store the result into map
memo[cur] = temp;
return temp;
}
// method returns maximum survival time
int getMaxSurvivalTime(int A,area Z)
{
if (A <= 0 || B <= 0)
return 0;
map< pair<int,int > memo;
// At first,we can step into any of the area
return
max(maxSurvival(A + X.a,memo));
}
// Driver code to test above method
int main()
{
area X(3,2);
area Y(-5,-10);
area Z(-20,5);
int A = 20;
int B = 8;
cout << getMaxSurvivalTime(A,B,Z);
return 0;
}
输出:
5
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。