You are given a rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer n. The goal is to replace each question mark with some positive integer from 1 to n, such that equality holds.
The only line of the input contains a rebus. It's guaranteed that it contains no more than 100 question marks, integer n is positive and doesn't exceed 1 000 000, all letters and integers are separated by spaces, arithmetic operations are located only between question marks.
The first line of the output should contain "Possible" (without quotes) if rebus has a solution and "Impossible" (without quotes) otherwise.
If the answer exists, the second line should contain any valid rebus with question marks replaced by integers from 1 to n. Follow the format given in the samples.
? + ? - ? + ? + ? = 42
Possible 9 + 13 - 39 + 28 + 31 = 42
? - ? = 1
Impossible
? = 1000000
Possible 1000000 = 1000000
做了好长时间,一点一点的思维向最优解靠拢,终于A掉了QAQ,o(≧v≦)o~~好棒。
#include <cstdio>
#include <queue>
#include <iostream>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const long long inf = 1e9;
const int MAXN = 1e5+7;
int n;
char s[110];
char ans[110];
int num[110];
int main()
{
int cnt = 0,num1 = 0,num2 = 0;
while(~scanf("%s",s))
{
if(s[0] == '=')break;
if(s[0] == '+')
{
ans[cnt++] = '+';
num1++;
}
else if(s[0] == '-')
{
ans[cnt++] = '-';
num2++;
}
}
scanf("%d",&n);
if(num1 == 0 && num2>0)puts("Impossible");//只有减号
else if(num1 == num2 && num1 == 0)printf("Possible\n%d = %d\n",n,n);//没有符号
else if(num1>0 && num2==0)//只有加号
{
if(num1>n-1)puts("Impossible");
else
{
puts("Possible");
printf("%d ",n-cnt);
for(int i = 0; i < cnt ; ++i)
{
printf("%c 1 ",ans[i]);
}
printf("= %d\n",n);
}
}
else//+-混合,一开始其实就是一个+号的
{
num1++;
if(num1>num2)
{
if(num2*n+n<num1)//一种极限情况
{
puts("Impossible");
return 0;
}
//如果在极限情况内的话,说明必定存在一种分配方案,这里采用均匀分配是最好的
int dert = n + num2*n;
int x = dert/num1 ;
int y = dert%num1;
if(!x)
{
puts("Impossible");
return 0;
}
puts("Possible");
if(y)
{
printf("%d ",x+1);
y--;
}
else
{
printf("%d ",x);
}
for(int i = 0; i < cnt ; ++i)
{
printf("%c ",ans[i]);
if(ans[i] == '-')
{
printf("%d ",n);
}
else
{
if(y)
{
printf("%d ",x+1);
y--;
}
else
{
printf("%d ",x);
}
}
}
printf("= %d\n",n);
}
else
{
if(num1*n-n<num2)
{
puts("Impossible");
return 0;
}
int dert = num1*n - n;
int x = dert/num2 ;
int y = dert%num2;
if(!x)
{
puts("Impossible");
return 0;
}
printf("Possible\n%d ",n);
for(int i = 0; i < cnt ; ++i)
{
printf("%c ",ans[i]);
if(ans[i] == '+')
{
printf("%d ",n);
}
else
{
if(y)
{
printf("%d ",x+1);
y--;
}
else
{
printf("%d ",x);
}
}
}
printf("= %d\n",n);
}
}
return 0;
}