Exact Change (贪心枚举)

D. Exact Change

[Link](Problem - D - Codeforces)

题意

给你一些数,你有 1 元 、 2 元 、 三 元 1元、2元、三元 12三种硬币,问你最少带多少个硬币可以将这些数都可以分别凑出来。

思路

​ 贪心的来看我们能多用 3 3 3就多用 3 3 3 3 的 余 数 最 多 有 0 , 1 , 2 3的余数最多有0,1,2 30,1,2,也就是我们最多带再带 一 个 1 , 一 个 2 一个1,一个2 12就能把所有的都拼出来,所以上界为 m a x n u m / 3 + 2 maxnum / 3 + 2 maxnum/3+2。但有的时候并不需要 1 或 2 1或2 12,还有的时候可以少带一个 3 3 3将一个余数为 1 1 1的转化为用两个 2 2 2拼出,例如 10 , 8 10,8 10,8最优解因该是 3 , 3 , 2 , 2 3,3,2,2 3,3,2,2四个硬币即可。

​ 发现贪心下界分类讨论不是很方便,但是经过刚才分析,我们发现,最多用一个 1 1 1,最多用两个 2 2 2,因此我们暴力的枚举用多少个 1 和 2 1和2 12,然后枚举每一个数判断一下当前用了这些 1 , 2 1,2 1,2后还需要多少个 3 3 3即可,注意一定是可以凑出的情况我们才比较,如果凑不出即当前选法无解置成正无穷即可。

Code

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>
#include <map>
#include <bitset>
#include <unordered_map>
#include <cmath> 
#include <stack>
#include <iomanip>
#include <deque> 
#include <sstream>
#define x first
#define y second
#define debug(x) cout<<#x<<":"<<x<<endl;
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef unsigned long long ULL;
const int N = 1e5 + 10, M = 2 * N, INF = 0x3f3f3f3f, mod = 1e9 + 7;
const double eps = 1e-8, pi = acos(-1), inf = 1e20;
#define tpyeinput int
inline char nc() {static char buf[1000000],*p1=buf,*p2=buf;return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;}
inline void read(tpyeinput &sum) {char ch=nc();sum=0;while(!(ch>='0'&&ch<='9')) ch=nc();while(ch>='0'&&ch<='9') sum=(sum<<3)+(sum<<1)+(ch-48),ch=nc();}
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int v = 0) {
	e[idx] = b, w[idx] = v, ne[idx] = h[a], h[a] = idx ++;
}
int n, m, k;
int a[N];
int main() {
	ios::sync_with_stdio(false), cin.tie(0);
	int T;
	cin >> T;
	while (T -- ) {
		cin >> n;
		for (int i = 0; i < n; i ++) cin >> a[i];
        
		int res = INF;
		for (int x1 = 0; x1 <= 1; x1 ++)	
			for (int x2 = 0; x2 <= 2; x2 ++) {
				int ans = 0;
				for (int i = 0; i < n; i ++) {
					int cnt = INF;
					for (int sx1 = 0; sx1 <= x1; sx1 ++)
						for (int sx2 = 0; sx2 <= x2; sx2 ++) {
							int v = a[i] - sx1 - sx2 * 2;
							if (v >= 0 && v % 3 == 0) {
								cnt = min(cnt, v / 3);
							}
						}
				ans = max(ans, cnt);
			}
			res = min(res, ans + x1 + x2);
	}
        
		cout << res << endl;
	}
	return 0;
}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值