codeforces1303D 贪心+位运算

本文探讨了一道算法题,通过位运算判断是否能通过一系列操作将一组2的幂次方数相加得到目标数n,若可行则输出最少操作次数。采用从低位到高位的策略,确保了操作的最优化。

1303D 1900
题意:给你一个数n和长度为m的数组,同时这m个数保证都是2的幂次方,问你是否可以通过对m中的数除2的操作,然后相加得到m,如果能打印最小的操作数,如果不能打印-1
思路:从题目中2的幂次方可以联想到这是一个和位运算有关的题目,如果分别把n和m中的数变成二进制来计算,从低位到高位,如果m中的数在二进制,该位为0,而n为1,那么就意味着,m中这个位要向前面的取一,即a[pos]–,而为什么是从低位到高位,而不是高位到低位,因为我们的低位是首先要满足的,而你要最优的操作数,如果从最高位开始,不知道是怎么计算,综上,代码也就可以出来了,当然还有一个从一开始就要判断的如果这m个数的和是小于n的话就不可能变成n,但如果是大于等于n的话就一定可以变成n。

#pragma GCC optimize("Ofast","inline","-ffast-math")
#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<bits/stdc++.h> 
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define int ll
typedef pair<int, int> pii;
#define rep(i, a, n) for(int i = a; i <= n; i++)
#define per(i, a, n) for(int i = n; i >= a; i--)
#define IOS std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define fopen freopen("file.in","r",stdin);freopen("file.out","w",stdout);
#define fclose fclose(stdin);fclose(stdout);
const int inf = 1e9;
const ll onf = 1e18;
const int maxn = 1e5+10;
inline int read(){
	int x=0,f=1;char ch=getchar();
	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
	while (isdigit(ch)){x=(x<<3)+(x<<1)+ch-48;ch=getchar();}
	return x*f;
}
inline void cf(){
	int t = read();
	while(t--){
		int n=read(), m=read(), a[65], sum = 0;
		memset(a,0,sizeof(a));
		rep(i,1,m){
			int x = read(), j = 0;
			sum += x;
			while(x>>j) j++;
			a[j-1]++;
		}
		if(n>sum) {printf("-1\n");continue;}
		int ans = 0, pos = 0;
		while(n||a[pos]<0){
			int tmp = n%2;n/=2;
			a[pos]-=tmp;
			if(a[pos]>=0) a[pos+1] += a[pos]/2;
			else a[pos+1]--, ans++;
			pos++;
		}
		printf("%lld\n", ans);
	}
	return ;
}
signed main(){
	cf();
	return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值