洛谷P1450 [HAOI2008]硬币购物(背包问题,容斥原理)

洛谷题目传送门
我实在是太弱了,第一次正儿八经写背包DP,第一次领会如此巧妙的容斥原理的应用。。。。。。

对每次询问都做一遍多重背包,显然T飞,就不考虑了

关键就在于每次询问如何利用重复的信息

我这么弱,当然是想不到容斥原理的啦

暂且先当成完全背包,每种硬币可使用无限次,预处理\(f\)数组,\(f[i]\)等于买价值\(i\)的东西的总方案数

然后就要从中减去不合法的。首先肯定会有一种硬币超额使用,第\(j\)中硬币等于说强制选了\(d_j+1\)个,剩下的依然随便选,那么第
\(j\)种硬币超额的不合法的方案数等于\(f[s-(d_j+1)*c_j]\),于是从答案里减去\(\sum_{j=1}^4f[s-(d_j+1)*c_j]\)

还要注意,第一种第二种都超额、第一种第三种都超额、第一种第四种都超额、第二种第三种都超额、第二种第四种都超额、第三种第四种都超额的方案在上一步中都被减了两次,所以额外都加一次回来。。。。。。(接着把容斥做下去就不说了)

复杂度降到\(O(4maxs+4×2^4tot)\),轻松通过

注意开longlong就好啦

#include<cstdio>
#define R register
typedef long long LL;
const int S=100009;
LL f[S]={1ll};
int main(){
    R int c[4],d[4],tot,i,j,k,now,s,ss,tmp;
    R LL ans;
    for(j=0;j<4;++j)scanf("%d",&c[j]);
    scanf("%d",&tot);
    for(j=0;j<4;++j)
        for(i=c[j];i<S;++i)
            f[i]+=f[i-c[j]];//完全背包预处理
    while(tot--){
        for(j=0;j<4;++j)scanf("%d",&d[j]);
        scanf("%d",&s);
        ans=f[s];
        for(ss=1;ss<=15;++ss){//二进制数枚举集合,容斥
            now=s;
            for(tmp=ss,j=k=0;tmp;tmp>>=1,++j)
                if(tmp&1)k^=1,now-=(d[j]+1)*c[j];
                //注意k的作用,判断奇偶
            if(now>=0)k?ans-=f[now]:ans+=f[now];
        }
        printf("%lld\n",ans);
    }
    return 0;
}

转载于:https://www.cnblogs.com/flashhu/p/8660393.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这道题目还可以使用树状数组或线段树来实现,时间复杂度也为 $\mathcal{O}(n\log n)$。这里给出使用树状数组的实现代码。 解题思路: 1. 读入数据; 2. 将原数列离散化,得到一个新的数列 b; 3. 从右往左依次将 b 数列中的元素插入到树状数组中,并计算逆序对数; 4. 输出逆序对数。 代码实现: ```c++ #include <cstdio> #include <cstdlib> #include <algorithm> const int MAXN = 500005; struct Node { int val, id; bool operator<(const Node& other) const { return val < other.val; } } nodes[MAXN]; int n, a[MAXN], b[MAXN], c[MAXN]; long long ans; inline int lowbit(int x) { return x & (-x); } void update(int x, int val) { for (int i = x; i <= n; i += lowbit(i)) { c[i] += val; } } int query(int x) { int res = 0; for (int i = x; i > 0; i -= lowbit(i)) { res += c[i]; } return res; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); nodes[i] = {a[i], i}; } std::sort(nodes + 1, nodes + n + 1); int cnt = 0; for (int i = 1; i <= n; ++i) { if (i == 1 || nodes[i].val != nodes[i - 1].val) { ++cnt; } b[nodes[i].id] = cnt; } for (int i = n; i >= 1; --i) { ans += query(b[i] - 1); update(b[i], 1); } printf("%lld\n", ans); return 0; } ``` 注意事项: - 在对原数列进行离散化时,需要记录每个元素在原数列中的位置,便于后面计算逆序对数; - 设树状数组的大小为 $n$,则树状数组中的下标从 $1$ 到 $n$,而不是从 $0$ 到 $n-1$; - 在计算逆序对数时,需要查询离散化后的数列中比当前元素小的元素个数,即查询 $b_i-1$ 位置上的值; - 在插入元素时,需要将离散化后的数列的元素从右往左依次插入树状数组中,而不是从左往右。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值