Codeforces Round #347 (Div. 2) B. Rebus

题目链接:

http://codeforces.com/contest/664/problem/B

题意:

给你一个等式,把等式左边的问号用1到n(n为等式右边的数)的数填好,使得等式成立

题解:

贪心求出最小最大值,如果n在这个范围则有解,否则无解。

构造解: 取最小值或最大值,然后从第一个数开始调整,直到等式成立为止。

代码:

 

#include<iostream>
#include<cstring>
#include<vector>
using namespace std;

const int maxn = 111;
const int INF = 1e9 + 7;

char str[maxn], sig[maxn];
int val[maxn],p1,p2;
int n;

void init() {
    p1 = 0, p2 = 0;
    sig[p1++] = '+';
}

int main() {
    init();
    while (scanf("%s", str) == 1 && str[0] != '=') {
        if (str[0] == '?') {
            
        }else{
            sig[p1++] = str[0];
        }
    }
    sig[p1] = '\0';
    scanf("%d", &n);
    int mi=0, ma=0;
    vector<int> ans;
    for (int i = 0; i < p1; i++) {
        if (sig[i] == '+') mi += 1,ma+=n,ans.push_back(1);
        else mi -= n,ma-=1,ans.push_back(n);
    }
    if (n >= mi&&n <= ma) {
        int dis = n-mi;
        for (int i = 0; i < p1; i++) {
            if (sig[i] == '+') {
                if (dis >= n - 1) {
                    ans[i] = n;
                    dis -= (n - 1);
                }
                else {
                    ans[i] += dis;
                    dis = 0;
                }
            }
            else {
                if (dis >= n - 1) {
                    ans[i] = 1;
                    dis -= (n - 1);
                }
                else {
                    ans[i] -= dis;
                    dis = 0;
                }
            }
            if (dis == 0) break;
        }
        printf("Possible\n");
        for (int i = 0; i < p1-1; i++) {
            printf("%d %c ", ans[i], sig[i + 1]);
        }
        printf("%d = %d\n", ans[p1 - 1], n);
    }
    else {
        printf("Impossible\n");
    }
    return 0;
}

 

posted @ 2016-05-31 21:23  fenicnn  阅读(196)  评论(0编辑  收藏  举报