POJ 3021 Analysis: DP algorithm

  1. Problem Solving
    There are now two currencies, M-group, each with a traditional currency and an IT currency. We are going to change these two currencies into a new one. The exchange method is that the square of traditional currency plus IT currency equals the square of new currency. Ask how many old currencies(contain traditional and IT) are used least.
    Input

2)Input:
Problems solving: n
For each problem, the amount for new currency: s
For each problem, kinds of currencies: m
m lines, each line contains 2 intergers, one for the value of traditional currency and one for the value of IT currency.
Output:
One interger: the minimum number of old currencies(contain traditional and IT).
If not, output “not possible”.

3)DP algorithm: DP algorithm not only lists all possible solutions, but also through calculations, see whether their are better solutions compared to the old solutions, which is dynamic optimization.
4) Analysis for this problem:
For this problem, DP algorithm is the best. The followings are the steps to use DP algorithm to solve this problem.
1. Define problem: lets make a list: dp[s][s]. For each element, dp[i][j], Let DP (I, J) store the minimum number of tuples (a, b) through which there are I traditional values and j IT values. After we calculated all the optimum DP[i][j], we need to determine whether i^2 + j^2 = s^2
2. State transition: nextly, we need to have a state transition when we calculate DP[i][j] stores the minimum number of tuples(a,b) through which there are i traditional values and j IT values. If there are i and j value and tuples, then traditional values increased a and IT values increased b. Else, nothing changed. Therefore, the state transition formula is dp[i][j]=min(dp[i][j],dp[i-a[k]][j-b[k]]-1)
3. After we processed DP, we just need to use a loop to process whether each i2+j2=s^2. If there is a dp[i][j] correspond to i2+j2=s^2, then output i+j, which is the total amount for old currencies. Else we need to output “not possible”.
5) The codes:
#include
#include
#include
using namespace std;
const int inf=1<<28;
int a[102],b[102],dp[302][302];
int main()
{
int n;
scanf("%d",&n);
while(n–)
{
int m,s;
scanf("%d%d",&m,&s);
int i,j,k;
for(i=0;i<m;i++)
{
scanf("%d%d",&a[i],&b[i]);
}
for(i=0;i<=s;i++)
{
for(j=0;j<=s;j++)
{
dp[i][j]=inf;
}
}
dp[0][0]=0;
for(i=0;i<=s;i++)
{
for(j=0;j<=s;j++)
{
for(k=0;k<m;k++)
{
if(i>=a[k] && j>=b[k])
{
dp[i][j]=min(dp[i][j],dp[i-a[k]][j-b[k]]+1);
}
}
}
}
int ans=inf;
for(i=0;i<=s;i++)
{
for(j=0;j<=s;j++)
{
if(ii+jjs*s)
{
ans=min(ans,dp[i][j]);
}
}
}
if(ans
inf)
{
printf(“not possible\n”);
continue;
}
printf("%d\n",ans);
}
return 0;
}

猜你喜欢

转载自blog.csdn.net/alex_yuqian/article/details/105154855