跳转至

题单

纯深搜 + 一点小剪枝

vjudge

剪枝 + 状态图遍历

vjudge

开心的金明

观察到 \(m \lt 25\),使用子集搜索。

状态:\((i, sum, res)\) 表示当前考虑第 \(i\) 个物品,之前花了 \(sum\) 元、价格与重要度乘积之和为 \(res\)。

转移:\((i, sum, res) \rightarrow (i + 1, sum ,res), (i + 1, sum + v_i, res + v_ip_i)\)。

总时间复杂度 \(O(2^m)\)。

健康的荷斯坦奶牛

题意

给定一头奶牛所需的 \(n\) 种维他命的数量,和 \(m\) 种饲料包含的 \(n\) 种维他命数量,每种饲料使用一次。求出使用饲料种数最少的方案,若存在多个方案,输出饲料编号字典序最小的那个一个。

搜索每种饲料是否选取,当搜索出一种选取饲料的方案,判断方案是否合法,并维护答案。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// lg-P1460
#include <iostream>
#include <climits>

using namespace std;

const int MAXN = 20;
const int MAXM = 30;

int w[MAXM], a[MAXN][MAXM], res[MAXN], ans[MAXN];
int ansc = INT_MAX, v, g;

void dfs(int x, int w[], int c){
  if (x == g + 1){
    bool f = 1;
    for (int i = 1; i <= v; i++){
      f &= w[i] <= 0;
    }
    if (f && c < ansc){
      ansc = c;
      for (int i = 1; i <= c; i++){
        ans[i] = res[i];
      }
    }
    return ;
  }
  res[c + 1] = x;
  for (int i = 1; i <= v; i++){
    w[i] -= a[x][i];
  }
  dfs(x + 1, w, c + 1);
  for (int i = 1; i <= v; i++){
    w[i] += a[x][i];
  }
  dfs(x + 1, w, c);
}

int main(){
  cin >> v;
  for (int i = 1; i <= v; i++){
    cin >> w[i];
  }
  cin >> g;
  for (int i = 1; i <= g; i++){
    for (int j = 1; j <= v; j++){
      cin >> a[i][j];
    }
  }
  dfs(1, w, 0);
  cout << ansc;
  for (int i = 1; i <= ansc; i++){
    cout << ' ' << ans[i];
  }
  return 0;
}

空间复杂度:记录所需维他命 \(O(n)\),记录饲料 \(O(n \times m)\),记录方案 \(O(m)\),总共 \(O(n \times m)\)。

时间复杂度:搜索选取方案 \(O(2^m)\),维护所需维他命量总共 \(O(n \times 2^m)\),记录一个选取方案最坏 \(O(m)\),总共 \(O((n + m)2^m)\)。