USACO-cha1-sec1.5 Superprime Rib

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 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
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;
}


你可能感兴趣的:(构造,ACM-USACO,DFS)