HDOJ 1016 Prime Ring Problem 暴搜DFS

🍑 OJ专栏


🍑 HDOJ 1016 Prime Ring Problem

在这里插入图片描述
输入

6
8

输出

Case 1:
1 4 3 2 5 6
1 6 5 2 3 4

Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2

🍑 题意

🍤 给定一个数 n,用 1~n 个数组一个成环,要求相邻的两数和 为 质数

🍑 思路

🍤 DFS 从第 1 位开始搜(不符合条件的直接不搜)
🍤 预处理素数表 O(n),判断素数 O(1)

🍑 AC code

import java.util.Arrays;
import java.util.Scanner;

public class Main
{
	static int n, N = 30;
	static boolean[] st = new boolean[N];// 记录每个数是否已经使用
	static int[] a = new int[N];//记录环序列
	static boolean[] p = new boolean[100];// 素数筛数组
	static int[] primes = new int[N];// 素数数组 (flase表示素数)
	static int idx;// 记录有几个素数

//	线性筛法初始化素数数组
	static void init()
	{
		p[0] = true;
		p[1] = true;
		for (int i = 2; i < 100; i++)
		{
			if (!p[i])
				primes[idx++] = i;
			for (int j = 0; primes[j] * i < 100; j++)
			{
				p[i * primes[j]] = true;
				if (i % primes[j] == 0)
					break;
			}
		}
	}

//	x 表示
	private static void dfs(int x, int cnt)
	{
		if (cnt == n)
		{
			int t = a[cnt] + a[1];
			if (!p[t])// 是质数
			{
				for (int i = 1; i < n; i++)
				    // System.out.printf("%d ",a[i]); // TLE?
					System.out.printf(a[i] + " ");// PE?
				
				System.out.println(a[n]);
			}
		}

		for (int i = 2; i <= n; i++)
		{
			if (st[i] || p[i + x])
				continue;
			st[i] = true;// 表示当前数以选
			a[++cnt] = i;
			dfs(i, cnt);
			cnt--;
			st[i] = false;
		}
	}

	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		int cnt = 1;
		init();// 预处理质数数组
		while (sc.hasNext())
		{
			n = sc.nextInt();
			Arrays.fill(st, false);
			a[1] = 1;
// 			if(cnt != 1)
// 			    System.out.println();
			System.out.println("Case " + (cnt++) + ":");
			dfs(1, 1);
			System.out.println();
		}
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值