Codeforces-663A-Rebus

来源:互联网 发布:java输出1到100的素数 编辑:程序博客网 时间:2024/04/29 23:24

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

题意:补充这个?使得式子满足,满足输出possible,然后输出任一解,否则输出impossible
题解:首先把+号变成1,-号变成-1,然后统计加号减号的差值,再一步一步去调整,num变量控制差值,使得最后与sum保持不变,若一样则possible反之则反之

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;char s[100005];int a[100005];int main(){    while(gets(s))    {        int t=0;        int l=strlen(s);        int num=0;        int d=1;        for(int i=0;i<l;i++)        {            if(s[i]=='+')  d=1;            else if(s[i]=='-') d=-1;            else if(s[i]=='?')            {                a[t++]=d;                num+=d;            }        }        int n=1,sum=0;        for(int i=l-1;i>=0;i--)        {            if(s[i]>='0'&&s[i]<='9')            {                sum+=(s[i]-'0')*n;                n*=10;            }        }        //printf("%d\n",sum);        for(int i=0;i<t;i++)        {            while(num<sum&&a[i]>0&&a[i]<sum)            {                num++;                a[i]++;            }            while(num>sum&&a[i]<0&&a[i]>-sum)            {                num--;                a[i]--;            }        }        int w=0;        if(num!=sum)        {            printf("Impossible");            continue;        }        printf("Possible\n");        //printf("%d",a[0]);        for(int i=0;i<l;i++)        {            if(s[i]!='?')                printf("%c",s[i]);            else printf("%d",abs(a[w++]));        }        printf("\n");    }    return 0;}
0 0
原创粉丝点击