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 from1 to n, such that equality holds.
The only line of the input contains a rebus. It's guaranteed that it contains no more than100 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 from1 to n. Follow the format given in the samples.
? + ? - ? + ? + ? = 42
Possible 9 + 13 - 39 + 28 + 31 = 42
? - ? = 1
Impossible
? = 1000000
Possible 1000000 = 1000000
题意:给你一个?+?+?-?=n的字符算式,符号?表示1->n的数,各个?中的可以重复相同,运算符只能是“+”,"-"且总共不会超过一百个。问是否存?+?+?-?=n在这样的等式,若存在则输出Possible并输出任意一个等式。若不存在则输出Impossible。解法:由于n《=100000的,dfs暴力搜索肯定的是不行的。我们可以先统计“+”,p,“-”q的个数(因为第一个数一定为+所以p的初值为1),由于等式中可以重复出现且最小值为1.我们可以先将所有?=1.则此时等式左边的和为sum=p-q;若sum>n我们只需要在符号位为“-”的值+1,让sum--直到sum==n。同理若sum<n我们只需要在符号位为“-”的值+1,让sum++直到sum==n。这个构造过程中?=n时,则对下一个?进行处理。若对于整个过程,能出现sum==n则这样的等是存在,否则则不存在。AC:#include <algorithm> #include <string> #include <iostream> #include <string.h> #include<stdio.h> #include<cmath> #include<vector> using namespace std; #define ll unsigned long long int const int maxn=1000009; char s[maxn]; int a[maxn],v[maxn]; int main() { int i,n,p,q,sum,cnt; gets(s); n=0; q=0; v[0]=1; cnt=p=1; for( i=0;i<strlen(s);i++) { if(s[i]=='+') { v[cnt++]=1; p++; } else if(s[i]=='-') { v[cnt++]=-1; q++; } if(s[i]=='=') break; }for(;i<strlen(s);i++) { if(s[i]>='0'&&s[i]<='9') { n=n*10+s[i]-'0'; } } sum=p-q; for( i=0;i<cnt;i++) { a[i]=1; } for( i=0;i<cnt;i++) { while(sum<n&&a[i]<n&&v[i]==1) { a[i]++; sum++; } while(sum>n&&a[i]<n&&v[i]==-1) { a[i]++; sum--; } } if(sum!=n) printf("Impossible\n"); else { printf("Possible\n"); printf("%d",a[0]); for( i=1;i<cnt;i++) { if(v[i]==1) { printf(" + %d",a[i]); } else if(v[i]==-1) { printf(" - %d",a[i]); } } printf(" = %d \n",n);} }