Loading [MathJax]/jax/output/CommonHTML/jax.js

Atcoder 123C 1, 2, 3 - Decomposition

Problem Statement

Given is a positive integer N. Consider a sequence of integers A=(A1,…,AK) that satisfies the conditions below:

  • ∑Ki=1Ai=N;
  • each Ai is a positive integer such that every digit in its decimal notation is 1, 2, or 3.

Find the minimum possible value of K, that is, the number of elements in such a sequence A.

Process T test cases per input file.

Constraints

  • 1≤T≤1000
  • 1≤N≤1018

Input

Input is given from Standard Input in the following format:

T
case1
case2
⋮⋮
caseT

Each case is in the following format:

N

Output

Print the answers.


Sample Input 1 Copy

Copy

5
456
10000
123
314
91

Sample Output 1 Copy

Copy

2
4
1
2
4

For each N, one optimal A is shown below.

  • For N=456: A=(133,323).
  • For N=10000: A=(323,3132,3232,3313).
  • For N=123: A=(123).
  • For N=314: A=(312,2).
  • For N=91: A=(22,23,23,23).

题目翻译

定义由1,2,3构成的数为“好数”。求出N最少可以被分解为多少个“好数”的和

共有T组数据

N<=1018,T<=1000

题目解析

首先有个结论:一定能够分解,且最多不会超过5个

f(x)表示x最少分解为多少个好数

n=x10 r=x mod 10

  • 1<=r<=3,且f(n)<=1f(x)=1
  • 2<=r<=6,且f(n)<=2f(x)=2
  • 3<=r<=9,且f(n)<=3f(x)=3
  • 4<=r<=9,且f(n)<=4f(x)=4
  • 0<=r<=2,且f(n1)<=4f(x)=4
  • 否则f(x)=5

记忆化搜索即可

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<unordered_map>
using namespace std;
typedef long long ll;
unordered_map<ll,int>mp;
int dfs(ll x){
    if (x==0) return 0;
    if (mp.count(x)) return mp[x];
    //cout<<x<<endl;
    ll n=x/10,r=x%10;
    int ans=0;
    int p=dfs(n);
    if (r>=1&&r<=3&&p<=1) ans=1;
    else if(r>=2&&r<=6&&p<=2) ans=2;
    else if (r>=3&&r<=9&&p<=3) ans=3;
    else if (r>=4&&r<=9&&p<=4) ans=4;
    else if (r>=0&&r<=2&&dfs(n-1)<=4) ans=4;
    else ans=5;
    mp[x]=ans;
    //cout<<ans<<endl;
    return ans;
}
int main(){
    int T;
    ll n;
    cin>>T;
    while (T--){
        scanf("%lld",&n);
        printf("%d\n",dfs(n));
    }
}
posted @   Z-Y-Y-S  阅读(82)  评论(0编辑  收藏  举报
编辑推荐:
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
点击右上角即可分享
微信分享提示