洛谷1450 [HAOI2008]硬币购物

本文介绍了一种利用容斥原理解决洛谷1450问题的方法,通过递归深度优先搜索来排除非法状态,实现了计算购买特定金额商品的方案数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接

  https://www.luogu.org/problem/show?pid=1450

题解

  第一次做这种容斥题,主要是学一下套路。

  令f[i]表示每种硬币都无限的情况下,买i块钱的东西有多少种方案数。那么对于每一次查询,你就要把不合法的减去,这里直接容斥就好了。容斥使用的是dfs。注意这里只需要把f[sum-(d[x]+1)*c[x]]减掉就行了,因为一旦选了(d[x]+1)个,再选任何一个x硬币就是不合法的了,已经包含了所有的方案数。

  再一点就是f[i]的计算,这里的f[i]是方案数,本质上是组合数,如果直接递推的话肯定不行,要枚举加入每种硬币,然后来做。如果直接for一层的话,可能出现(1,2)(2,1)这种重复的情况。

代码

//容斥原理
#include <cstdio>
#include <algorithm>
#define ll long long
#define maxn 100100
using namespace std;
ll f[maxn], c[5], d[5], ans;
ll read(ll x=0)
{
	char c=getchar();
	while(c<48 or c>57)c=getchar();
	while(c>=48 and c<=57)x=x*10+c-48,c=getchar();
	return x;
}
void init()
{
	ll i, j;
	for(i=1;i<=4;i++)c[i]=read();
	f[0]=1;
	for(i=1;i<=4;i++)
		for(j=c[i];j<=100000;j++)
			f[j]+=f[j-c[i]];
}
inline void dfs(ll pos, ll k, ll sum)
{
	if(sum<0)return;
	if(pos>4)
	{
		if(k&1)ans-=f[sum];
		else ans+=f[sum];
		return;
	}
	dfs(pos+1,k,sum);
	dfs(pos+1,k+1,sum-c[pos]*(d[pos]+1));
}
int main()
{
	ll T, i, s;
	init();
	for(T=read();T;T--)
	{
		for(i=1;i<=4;i++)d[i]=read();s=read();
		ans=0;
		dfs(1,0,s);
		printf("%lld\n",ans);
	}
	return 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、付费专栏及课程。

余额充值