算法作业——集装箱装载问题(回溯)

#include 
using namespace std;

typedef long long ll;

const int maxn = 1e4 + 10;

int n;
int c1, c2;
int w[maxn];
vector<bool> ans;
int bestw;
int r;

void dfs(int cur, int now, int rest, vector<bool> & res) 
{
    if(rest + now < bestw) {
        return;
    }
    if(cur > n) {
        if(now > bestw) {
            bestw = now;
            ans = res;
        }
        return ;
    }
    // 装
    if(c1 >= now + w[cur]) {
        res[cur] = 1;
        dfs(cur+1, now + w[cur], rest - w[cur], res);
        res[cur] = 0;
    }
    // 不装
    dfs(cur+1, now, rest - w[cur], res);
}

int main()
{
    // freopen("/Users/maoxiangsun/MyRepertory/acm/code/i.txt", "r", stdin);
    bestw = 0;
    cin >> c1 >> c2;
    cin >> n;
    for(int i = 1; i <= n; i++) {
        cin >> w[i];
        r += w[i];
    }
    vector<bool> res(maxn, false);  
    dfs(1, 0, r, res);
    cout << bestw << endl;
    cout << "集装箱1:";
    for(int i = 1; i <= n; i++) {
        if(ans[i]) {
            cout << i << " ";
        }
    }
    cout << endl;
    cout << "集装箱2:";
    for(int i = 1; i <= n; i++) {
        if(!ans[i]) {
            cout << i << " " ;
        }
    }
    return 0;
}

你可能感兴趣的:(算法作业——集装箱装载问题(回溯))