题解:AT_abc404_d [ABC404D] Goin' to the Zoo

· · 题解

题目大意

有 N 个动物园和 M 种动物,每去一次动物园就要交一次门票钱,然后就能够看这个动物园里的所有动物一次。求看每种动物两次至少要花多少钱。

思路

看到 1 \le N \le 10 这么小的数据范围,直接想到 DFS 爆搜。

枚举每个动物园,有三种情况:

  1. 不去
  2. 去一次
  3. 去两次

还要注意:十年 OI 一场空,不开 long long 见祖宗。

时间复杂度 O(3^N \times M),可以通过此题。

代码

AC 记录

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

typedef long long lld;

lld a[110],b[110],ans=1e18;
int n,m;
vector<int> v[110];

bool check(){
    int f = 1;
    for(int i = 1; i <= m; i++){
        f = f && b[i]>=2;
    }
    return f;
}
void dfs(int step,lld s){
    if(step > n){
        if(check()){
            ans = min(ans,s);
        }
        return;
    }
    dfs(step+1,s);
    for(int i : v[step]){
        b[i]++;
    }
    dfs(step+1,s+a[step]);
    for(int i : v[step]){
        b[i]--;
    }
    for(int i : v[step]){
        b[i] += 2;
    }
    dfs(step+1,s+a[step]*2);
    for(int i : v[step]){
        b[i] -= 2;
    }
}

int main(){
    int k,t;
    cin>>n>>m;
    for(int i = 1; i <= n; i++){
        cin>>a[i];
    }
    for(int i = 1; i <= m; i++){
        cin>>k;
        while(k--){
            cin>>t;
            v[t].push_back(i);
        }
    }
    dfs(1,0);
    cout<<ans;
    return 0;
}