您的位置:首页 > 编程语言 > C语言/C++

SGU108 数学题 Math

2014-01-01 17:21 363 查看
题目:一个数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;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sgu 数学 C++ 筛法