USACO-cha1-sec1.5 Superprime Rib

本文介绍了一个算法问题,即如何找出所有长度为N的超级素数序列。超级素数是指从第一位到最后一位的所有连续子序列都是素数的整数。文章通过深度优先搜索(DFS)的方法实现了这一目标,并给出了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Superprime Rib

Butchering Farmer John's cows always yields the best prime rib. You can tell prime ribs by looking at the digits lovingly stamped across them, one by one, by FJ and the USDA. Farmer John ensures that a purchaser of his prime ribs gets really prime ribs because when sliced from the right, the numbers on the ribs continue to stay prime right down to the last rib, e.g.:

     7  3  3  1

The set of ribs denoted by 7331 is prime; the three ribs 733 are prime; the two ribs 73 are prime, and, of course, the last rib, 7, is prime. The number 7331 is called a superprime of length 4.

Write a program that accepts a number N 1 <=N<=8 of ribs and prints all the superprimes of that length.

The number 1 (by itself) is not a prime number.

PROGRAM NAME: sprime

INPUT FORMAT

A single line with the number N.

SAMPLE INPUT (file sprime.in)

4

OUTPUT FORMAT

The superprime ribs of length N, printed in ascending order one per line.

SAMPLE OUTPUT (file sprime.out)

2333
2339
2393
2399
2939
3119
3137
3733
3739
3793
3797
5939
7193
7331
7333
7393

————————————————————回家的分割线————————————————————

前言:明天就要回家过暑假啦!虽然只有短短20天,但是还是不能荒废的!
思路:这道题是典型的构造,很容易就会发现首位必须是2 3 5 7,其他都只能是 1 3 7 9。

既然如此那就好办了,dfs就好了。但其实我还是不会写的,基础太渣,写不出来就看了一下别人的。首先是临界条件:深度为n(数字长度)。到了临界点怎么办呢?

两个参数表示状态:当前值;深度。到了临界点打印当前值就好了。在此之前需要判断当前值是不是素数。然后是没到临界点的时候。因为有四个数字可以填,所以for(int i = 0; i < 4; i++)。填数字就是改变状态。dfs(cur+x, depth+1)。唉……本来应该会写的。这都能忘。

代码如下:

/*
ID: j.sure.1
PROG: sprime
LANG: C++
*/
/****************************************/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <string>
#include <iostream>
using namespace std;
/****************************************/
int p1[] = {2, 3, 5, 7}, p2[] = {1, 3, 7, 9};
int n, sp = 0;

bool prime(int a)
{
	if(a == 1)
		return false;
	for(int i = 2; i*i <= a; i++) {
		if(a % i == 0)
			return false;
	}
	return true;
}

void dfs(int cur, int depth)
{
	if(!prime(cur))
		return ;
	if(depth == n) {
		printf("%d\n", cur);
		return ;
	}
	for(int i = 0; i < 4; i++) {
		dfs(cur*10 + p2[i], depth+1);
	}
}

int main()
{
	freopen("sprime.in", "r", stdin);
	freopen("sprime.out", "w", stdout);
	scanf("%d", &n);
	if(n == 1) {
		printf("2\n3\n5\n7\n");
	}
	//2333
	else {
		for(int i = 0; i < 4; i++) {
			dfs(p1[i], 1);
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值