标签:线性筛,dfs
Description
阴天傍晚车窗外
未来有一个人在等待
向左向右向前看
爱要拐几个弯才来
我遇见谁会有怎样的对白
我等的人他在多远的未来
我听见风来自地铁和人海
我排着队拿着爱的号码牌
城市中人们总是拿着号码牌,不停寻找,不断匹配,可是谁也不知道自己等的那个人是谁。可是燕姿不一样,燕姿知道自己等的人是谁,因为燕姿数学学得好!燕姿发现了一个神奇的算法:假设自己的号码牌上写着数字S,那么自己等的人手上的号码牌数字的所有正约数之和必定等于S。
所以燕姿总是拿着号码牌在地铁和人海找数字(喂!这样真的靠谱吗)可是她忙着唱《绿光》,想拜托你写一个程序能够快速地找到所有自己等的人。
Input
输入包含k组数据(k<=100)对于每组数据,输入包含一个号码牌S
Output
对于每组数据,输出有两行,第一行包含一个整数m,表示有m个等的人,第二行包含相应的m个数,表示所有等的人的号码牌。注意:你输出的号码牌必须按照升序排列。
Sample Input
42
Sample Output
3
20 26 41
HINT
对于100%的数据,有S<=2*10*9
分析:
这题需要一些数学基础,知道约数和定理,不知道的出门右转百度百科
对于一个数n,分为两种情况讨论
1.n-1为质数,那么n-1存放答案的num数组
2. 对于每一个未被搜索过且平方小于当前数的质数,则枚举所有可能符合题意的情况进行递归搜索
时间复杂度并不是很会分析……
Code
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#define rep(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
const int maxn=5e4;
int prime[maxn],cnt=0,ans,num[maxn],n;
bool not_prime[maxn];
void getprime()
{
rep(i,2,maxn){
if(!not_prime[i])prime[++cnt]=i;
for(int j=1;prime[j]*i<=maxn&&j<=cnt;j++){
not_prime[i*prime[j]]=1;
if(i%prime[j]==0)break;
}
}
}
bool isprime(int x)
{
if(x==1)return false;
if(x<=maxn)return !not_prime[x];
for(int i=1;prime[i]*prime[i]<=x;i++)
if(x%prime[i]==0)return false;
return true;
}
void dfs(int last,int now,int tot)
{
if(tot==1){num[++ans]=now;return;}
if(tot-1>prime[last]&&isprime(tot-1))num[++ans]=now*(tot-1);
for(int i=last+1;prime[i]*prime[i]<=tot;i++)
for(int tnum=prime[i]+1,t=prime[i];tnum<=tot;t*=prime[i],tnum+=t)
if(tot%tnum==0)dfs(i,now*t,tot/tnum);
}
int main()
{
getprime();
while(scanf("%d",&n)!=EOF){
ans=0;dfs(0,1,n);
sort(num+1,num+1+ans);
printf("%d\n",ans);
rep(i,1,ans)printf("%d%c",num[i],i==ans?'\n':' ');
}
return 0;
}