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<=10^{18},T<=1000\)

题目解析

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

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

\(n=\lfloor \frac{x}{10} \rfloor \ r=x \ mod \ 10\)

  • \(1<=r<=3\),且\(f(n)<=1\)\(f(x)=1\)
  • \(2<=r<=6\),且\(f(n)<=2\)\(f(x)=2\)
  • \(3<=r<=9\),且\(f(n)<=3\)\(f(x)=3\)
  • \(4<=r<=9\),且\(f(n)<=4\)\(f(x)=4\)
  • \(0<=r<=2\),且\(f(n-1)<=4\)\(f(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 @ 2021-08-12 23:41  Z-Y-Y-S  阅读(73)  评论(0编辑  收藏  举报