time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.
Input
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.
Output
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.
Examples
input
? + ? - ? + ? + ? = 42
output
Possible
9 + 13 - 39 + 28 + 31 = 42
input
? - ? = 1
output
Impossible
input
? = 1000000
output
Possible
1000000 = 1000000
【题解】
一开始问号前面如果是加号则为1,如果是减号则为-1;
这个时候,如果总和小于所需的;
则把大于0的数字递增直到这个数字等于n或者已经达到了要求;小于0的则不能动(前面是负号);
如果总和大于所需的;
则把数字小于0的再减少一点(当然也不能小于-n);
这样可以递减总和。
具体的看代码;
如果以上操作都不能满足总和为n则输出无解信息;
一开始的数字初始化很巧妙;
#include <cstdio>
#include <cmath>
#include <set>
#include <map>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <stack>
#include <string>
#define LL long long
using namespace std;
const int MAXN = 2000;
char t;
int a[2000] = {0},now = 0,total = 1,n;
void input_LL(LL &r)
{
r = 0;
char t = getchar();
while (!isdigit(t)) t = getchar();
LL sign = 1;
if (t == '-')sign = -1;
while (!isdigit(t)) t = getchar();
while (isdigit(t)) r = r * 10 + t - '0', t = getchar();
r = r*sign;
}
void input_int(int &r)
{
r = 0;
char t = getchar();
while (!isdigit(t)) t = getchar();
int sign = 1;
if (t == '-')sign = -1;
while (!isdigit(t)) t = getchar();
while (isdigit(t)) r = r * 10 + t - '0', t = getchar();
r = r*sign;
}
int main()
{
//freopen("F:\rush.txt", "r", stdin);
a[++now] = 1;
while (cin>>t && t!='=')
{
if (t == '+')
a[++now] = 1,total++;
else
if (t== '-')
a[++now] = -1,total--;
}
input_int(n);
for (int i = 1;i <= now;i++)
if (a[i] > 0)
{
while (a[i]<n && total < n)
a[i]++,total++;
}
else
if (a[i] < 0)
{
while (a[i]>-n && total > n)
a[i]--,total--;
}
if (total!=n)
puts("Impossible");
else
{
puts("Possible");
printf("%d ",a[1]);
for (int i =2;i <= now;i++)
printf("%c %d ",a[i]>0?'+':'-',abs(a[i]));
printf("= %d
",n);
}
return 0;
}