装货物(搜索)

在这里插入图片描述
解题思路:
这道题目标准答案应该是动态规划,但是考虑到这里的n非常小,可以通过DFS来解决,增加一种思路,应该是搜索每个货物应该放的箱子的编号。

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1e4 + 10;
const int INF = 0x3f3f3f3f;
int T;
int n, x, w;
int a[N];
int t[N];
bool dfs(int d) {
    if (d == n + 1)return true;
    for (int i = 1; i <= min(x, d); i++) {
        if (t[i] + a[d] <= w) {
            t[i] += a[d];
            if (dfs(d + 1))return true;
            t[i] -= a[d];
        }
    }
    return false;
}
int main() {
    cin >> T;
    while (T--) {
        cin >> n >> x >> w;
        for (int i = 1; i <= n; i++)scanf("%d", &a[i]), t[i] = 0;
        if (dfs(1))puts("Yes");
        else puts("No");
    }
    return 0;
}
发布了165 篇原创文章 · 获赞 11 · 访问量 4885

猜你喜欢

转载自blog.csdn.net/weixin_43784305/article/details/105231375