[POJ 1416]Shredding Company[DFS]

题目链接: [POJ 1416]Shredding Company[DFS]

题意分析:

给出数字a和字符串b。问:字符串b能否切割后,使得每个数字相加,和最接近a但不超过a,如果有多组解,输出"rejected",无解输出"error",输出最接近的那个数和切割方案。

解题思路:

字符串长度最多6。那么就枚举当前位是否切割,用vector记录切割位置,p代表当前访问的位,sum代表当前方案能得到的和。有这三个状态dfs即可。

个人感受:

看似麻烦,实则还好。

具体代码如下:

#include<algorithm>
#include<cctype>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<sstream>
#include<stack>
#include<string>
#define ll long long
#define pr(x) cout << #x << " = " << (x) << '\n';
using namespace std;

const int INF = 0x7f7f7f7f;
const int MAXN = 1e6 + 111;

bool flag;
string b;
int ans, a;
vector<int> apos;

void dfs(int p, int sum, vector<int> pos) {
    if (p == b.length()) {
        int last = pos.back(), tsum = 0;
        for (int i = last; i < p; ++i) {
            tsum *= 10;
            tsum += b[i] - '0';
        }
        sum += tsum;
        if (sum <= a) {
            if (sum > ans) {
                ans = sum;
                apos = pos;
                flag = 0;
            }
            else if (sum == ans) {
                flag = 1;
            }
        }
        return;
    }

    // 不切
    dfs(p + 1, sum, pos);

    // 切
    if (p != 0) {
        int last = pos.back(), tsum = 0;
        for (int i = last; i < p; ++i) {
            tsum *= 10;
            tsum += b[i] - '0';
        }
        pos.push_back(p);
        dfs(p + 1, sum + tsum, pos);
    }
    return;
}

int main()
{
    while (cin >> a >> b) {
        if (a == 0 && b == "0") break;
        ans = -1;
        apos.clear();
        vector<int> pos;
        pos.push_back(0);
        dfs(0, 0, pos);

        if (ans == -1) cout << "error\n";
        else if (flag) cout << "rejected\n";
        else {
            apos.push_back(b.length());
            cout << ans;
            for (int i = 1; i < apos.size(); ++i) {
                cout << ' ';
                for (int j = apos[i - 1]; j < apos[i]; ++j)
                    cout << b[j];
            }
            cout << '\n';
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值