Time limit
1000 ms
Memory limit
262144 kB
George met AbdelKader in the corridor of the CS department busy trying to fix a group of incorrect equations. Seeing how fast he is, George decided to challenge AbdelKader with a very large incorrect equation. AbdelKader happily accepted the challenge!
Input
The first line of input contains an integer N (2 ≤ N ≤ 300), the number of terms in the equation.
The second line contains N integers separated by a plus + or a minus -, each value is between 1 and 300.
Values and operators are separated by a single space.
Output
If it is impossible to make the equation correct by replacing operators, print - 1, otherwise print the minimum number of needed changes.
Examples
Input
7
1 + 1 - 4 - 4 - 4 - 2 - 2
Output
3
Input
3
5 + 3 - 7
Output
-1
视作01背包,由于题目数据限制,我们可以得知容量为-90000到90000,由于负数的特殊性,我们对其加上修正值90000便于操作。
i为第几个物品,j为背包容量,Dp[i][j]表示在第i个物品时,使剩余容量为j时的操作次数(改变符号的次数)
ac代码
int dp[305][180005];
int main()
{
int n;
cin>>n;
char b;
int al[305];
cin>>al[1];
int sum=al[1];
for(int n1=2;n1<=n;n1++)
{
getchar();
cin>>b;
getchar();
cin>>al[n1];
sum+=al[n1];
if(b=='-')
{
al[n1]=-al[n1];
}
}
if(sum%2==1)
{
cout<<-1<<endl;
}
else
{
for(int n1=1;n1<=n;n1++)
{
for(int j=0;j<=2*sum;j++)
{
dp[n1][j]=99999;
}
}
//for(int j=0;j<=sum;j++)
dp[1][sum/2+al[1]]=0;
for(int n1=2;n1<=n;n1++)
{
for(int j=0;j<=sum;j++)
{
if(j>=al[n1])
{
dp[n1][j]=min(dp[n1-1][j-al[n1]],dp[n1][j]);
}
if(j>=-al[n1])
{
dp[n1][j]=min(dp[n1-1][j+al[n1]]+1,dp[n1][j]);
}
}
}
if(dp[n][sum/2]>=n)
{
cout<<-1<<endl;
}
else
{
cout<<dp[n][sum/2]<<endl;
}
}
}