思路
一个 “
x
=
a
+
b
x = a + b
x=a+b” 的 问题
考虑枚举
看到2的幂次考虑到二进制
显然一个数可以被2的幂次和构成
答案最大为二进制表示下1的个数
由于还存在阶乘,答案 ans 可能会小
由于阶乘的增长很快,当n到达15时就超过了数据量1e12
故可以通过二进制枚举有哪些阶乘被使用,用x减去这些阶乘
再用二进制统计1的个数,求最小值;
具体看代码qwq
Code
// Problem: C. Factorials and Powers of Two
// Contest: Codeforces - Codeforces Round #774 (Div. 2)
// URL: https://codeforces.com/contest/1646/problem/C
// Memory Limit: 256 MB
// Time Limit: 3000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
using namespace std;
#define _orz ios::sync_with_stdio(false),cin.tie(0)
#define mem(str,num) memset(str,num,sizeof(str))
#define forr(i,a,b) for(int i = a;i <= b;i++)
#define forn(i,n) for(int i = 0; i < n; i++)
#define all(a) (a.begin(),a.end())
#define dbg() cout << "0k!" << endl;
//#define _DEBUG
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int N = 1e6+10;
const ll MOD = 1e9+7;
ll fct[20];
void so1ve(){
ll x; cin>> x;
// 暴力枚举阶乘的情况 取最小值
ll res = inf;
ll sum = (1LL<<16);
for(int i = 0;i < sum;i++){
ll t = x;
ll cnt = 0;
for(int j = 0; j<= 15;j++){
if(i & (1 << j)){
t -= fct[j];
cnt++;
}
}
if(t >= 0) res = min(res,cnt+__builtin_popcountll(t));
}
cout << res << endl;
}
int main()
{
#ifdef _DEBUG
//freopen("input.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
int t; cin >> t;
fct[0] = 1;
for(int i = 1;i <= 15;i++){
fct[i] = fct[i-1]*i;
}
while(t--) so1ve();
return 0;
}
总结 遇到类似 x =a+b 相关问题考虑如何枚举答案