SGU108 数学题 Math

题目:一个数n,d(n)是n的各个位之和与它本身的和,比如d(35) = 35 + 3 + 5 = 43。n成为d(n)的产生数。现在给你一个数N和K,以及K个数Sk,问1-N有多少个自我数(没有产生数),以及第Sk个自我数是多少。

Problem: For any positive integer n, define d(n) to be n plus the sum of the digits of n. For example, d(35) = 35 + 3 + 5 = 43. n is called the generator of d(n). Now give you N, K and K numbers Sk. Please answer the following two questions: 1. How many self-numbers(a number without generator) between 1-N? 2. What is the Sk-th self-number?

解法:我们用O(n)来一边求,一边记录,方法类似于质数筛法。考虑到空间限制,布尔数组用滚动数组。

Solution: We can calculate each number and record the answer in O(n). Considering the space limit, we use rolling array here.

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 1000
struct data {
       int c,id;
}a[5010],b[5010];
bool f[1010];
int n,k,pnum,now,cnt;
int d(int x) {
    int s = x;
    while (x) {
          s += x%10;
          x /= 10;
    }
    return s;
}
bool cmp1(data a, data b) {
     if (a.c<b.c) return true;
     return false;
}
bool cmp2(data a, data b) {
     if (a.id<b.id) return true;
     return false;
}
int main() {
    while (~scanf("%d%d",&n,&k)) {
          memset(a,0,sizeof(a));
          for (int i=1;i<=k;i++) {
              scanf("%d",&a[i].c);
              a[i].id = i;
          }
          sort(a+1,a+k+1,cmp1);    
          
          pnum = 0;
          cnt = 1;
          now = 1;
          memset(f,0,sizeof(f));
          while (now<=n) {
                if (!f[now%N]) {
                   pnum++;
                   while (pnum==a[cnt].c) {
                      b[cnt].c = now;
                      b[cnt].id = a[cnt].id;
                      cnt++;
                   }
                }
                else f[now%N] = false;
                f[d(now)%N] = true;
                now++;
          }
          
          sort(b+1,b+k+1,cmp2);
          printf("%d\n",pnum);
          for (int i=1;i<k;i++)
              printf("%d ",b[i].c);
          printf("%d\n",b[k].c);
    }
    return 0;
}
                     


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值