洛谷P1218 [USACO1.5]特殊的质数肋骨 Superprime Rib

时间:2023-03-09 09:02:02
洛谷P1218 [USACO1.5]特殊的质数肋骨 Superprime Rib

P1218 [USACO1.5]特殊的质数肋骨 Superprime Rib

    • 284通过
    • 425提交
  • 题目提供者该用户不存在
  • 标签USACO
  • 难度普及-

提交  讨论  题解

最新讨论

  • 超时怎么办?

题目描述

农民约翰的母牛总是产生最好的肋骨。你能通过农民约翰和美国农业部标记在每根肋骨上的数字认出它们。农民约翰确定他卖给买方的是真正的质数肋骨,是因为从右边开始切下肋骨,每次还剩下的肋骨上的数字都组成一个质数,举例来说: 7 3 3 1 全部肋骨上的数字 7331是质数;三根肋骨 733是质数;二根肋骨 73 是质数;当然,最后一根肋骨 7 也是质数。 7331 被叫做长度 4 的特殊质数。写一个程序对给定的肋骨的数目 N (1<=N<=8),求出所有的特殊质数。数字1不被看作一个质数。

输入输出格式

输入格式:

单独的一行包含N。

输出格式:

按顺序输出长度为 N 的特殊质数,每行一个。

输入输出样例

输入样例#1:
4
输出样例#1:
2333
2339
2393
2399
2939
3119
3137
3733
3739
3793
3797
5939
7193
7331
7333
7393

说明

题目翻译来自NOCOW。

USACO Training Section 1.5

分析:很自然的想到了枚举这个长度的数,不断地尝试,然后发现TLE,为什么呢?因为如果不断地删数字可能一开始是质数,但是到最后一个就不是质数了,所以考虑从低位向高位搜索,这样也可以保证答案是有序的.

60分算法:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm> using namespace std; int n,ans[],num; int power(int x,int d)
{
for (int i = ; i <= x; i++)
d *= ;
return d;
} bool panduan(int x)
{
if (x == )
return false;
for (int i = ; i * i <= x; i++)
if (x % i == )
return false;
return true;
} bool check(int x)
{
while (x)
{
if (!panduan(x))
return false;
x /= ;
}
return true;
} int main()
{
scanf("%d", &n);
for (int i = power(n - , );i <= power(n - , ); i++)
{
if (check(i))
ans[++num] = i;
}
sort(ans + , ans + + num);
for (int i = ; i <= num; i++)
printf("%d\n", ans[i]); return ;
}

100分算法:

#include<iostream>
#include<cstdio>
using namespace std;
int n;
bool check(int x)
{
if (x == )
return ;
for (int i = ;i*i <= x;i++)
if (x%i == )
return ;
return ;
}
void dfs(int u, int fa)
{
for (int i = ;i <= ;i++)
if (check(fa * + i))
{
if (u == n)
printf("%d\n", fa * + i);
else
dfs(u + , fa * + i);
}
}
int main()
{
scanf("%d", &n);
dfs(, ); return ;
}