Codeforces Round #441 (Div. 2) C. Classroom Watch


传送们

题目分析

题意:给你一个数(x),让你求出是否存在若干个数(n(n< x))使得(n)与其每一位数字的和等于(x)

我的做法本质上还是暴力枚举,但是可以通过一系列的限制来减少枚举的次数,使得较快的求出答案。在最坏情况下,一个长度为(k)的数字(n)与其每位的数字和跟(x)的差值不超过(9 imes (k-1))。所以我们可以从(9 imes (k-1))枚举到(n),即使在(10^{9})的极限情况下,最差也需要枚举(81)次,算是很少的枚举量了

但是这道题直接暴力也是能过的

AC代码

#include <bits/stdc++.h>
using namespace std;

vector<int> ans;
int n, k;
char s[1000];

// 求数字的长度
inline int count() {
    int t = n, cnt = 0;
    while(t) { 
        t /= 10;
        cnt ++;
    }
    int x = n - 9 * (cnt);
    return x <= 0 ? 0 : x;
}

int main() {
    scanf("%d", &n);  
    
    for(int i = count(); i < n; i++) {
        int sum = i;
        sprintf(s, "%d", i);
        
        // 将数字转化为字符串,然后求每位的和
        for(int j = 0; s[j]; j++) {
            sum += s[j] - '0';
        }
        if(sum == n) ans.push_back(i); // 将符合条件的答案储存一下
    }
    
    int f = ans.size();
    cout << f << '
';
    if(f) for(auto v : ans ) cout << v << '
';
    
    return 0;
}
原文地址:https://www.cnblogs.com/FrankOu/p/14556318.html