状压dp

感谢小助理的帮助

 

14564: Get Everything

时间限制: 1 Sec  内存限制: 128 MB
提交状态

题目描述

We have N locked treasure boxes, numbered 1 to N.
A shop sells M keys. The i-th key is sold for ai yen (the currency of Japan), and it can unlock bi of the boxes: Box ci1, ci2, ..., cibi. Each key purchased can be used any number of times.
Find the minimum cost required to unlock all the treasure boxes. If it is impossible to unlock all of them, print −1.

Constraints
·All values in input are integers.
·1≤N≤12
·1≤M≤103
·1≤ai≤105
·1≤bi≤N
·1≤ci1<ci2<...<cibi≤N

 

输入

Input is given from Standard Input in the following format:

N M
a1 b1
c11 c12 ... c1b1
:
aM bM
cM1 cM2 ... cMbM

输出

Print the minimum cost required to unlock all the treasure boxes. If it is impossible to unlock all of them, print −1.

样例输入 Copy

【样例1】
2 3
10 1
1
15 1
2
30 2
1 2
【样例2】
12 1
100000 1
2
【样例3】
4 6
67786 3
1 3 4
3497 1
2
44908 3
2 3 4
2156 3
2 3 4
26230 1
2
86918 1
3

样例输出 Copy

【样例1】
25
【样例2】
-1
【样例3】
69942

提示

样例1解释
We can unlock all the boxes by purchasing the first and second keys, at the cost of 25 yen, which is the minimum cost required.
样例2解释
We cannot unlock all the boxes.

标签

状压DP

#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;

const int inf=0x3f3f3f3f;
int n,m;

struct node{
     int cost,num;
}nd[100005];

int f[1005][(1<<12)+5];//1左移12位再加5

int main()
{
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int b;
        scanf("%d%d",&nd[i].cost,&b);
        int t=0;
        for(int j=1;j<=b;j++)
        {
              int temp;
              scanf("%d",&temp);
              t|=(1<<(temp-1));///1本来就在第一个位,所以要到第temp位,只需要向左移动temp-1位
        }
        nd[i].num=t;
    }
    memset(f,inf,sizeof(f));
    f[0][0]=0;///很重要
    for(int i=1;i<=m;i++)
    {
        for(int j=0;j<(1<<n);j++)///n个锁
        {
            int kk=j|nd[i].num;///对应每个锁选不选
            f[i][kk]=min(f[i][kk],f[i-1][j]+nd[i].cost);
            f[i][j]=min(f[i][j],f[i-1][j]);///
        }
    }
    if(f[m][(1<<n)-1]!=inf)///1向左移动12,相当于1000000000000,然而12个位置都为1,即(111111111111)=(1000000000000)-1
        printf("%d\n",f[m][(1<<n)-1]);
    else printf("-1");
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值