码迷,mamicode.com
首页 > 其他好文 > 详细

Prime Ring Problem

时间:2016-04-24 00:48:51      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:

Problem Description

A ring is compose of n circles as shown in diagram. Put natural number 1, 2, ..., n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.

Note: the number of first circle should always be 1.

技术分享
 

 

Input
n (0 < n < 20).
 
Output
The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order.

You are to write a program that completes above process.

Print a blank line after each case.
 
Sample Input
6 8
 
Sample Output
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这些数的组合,使的相邻的两个数之和为素数,头与尾也算。
思路:利用深搜和回溯,和n皇后问题有异曲同工之妙,只不过判定的条件改变了,n皇后问题条件为同行同列,对角线不能有其他皇后,而这个为相邻之间的数之和为素数。
 
代码:

#include <iostream>
#include<string.h>
using namespace std;
int a[25];
bool vis[25];
int n;

//输出组合好的数组
void output(){
  for(int i = 1;i <= n;i++){
    if(i==n)
      cout << a[i] << endl;
    else
      cout << a[i] << " ";
  }
}

//判断一个数是不是素数

bool prime(int num){
  if(num == 1)return false;
  if(num == 2 || num == 3)return true;
  int i;
  for(i=2;i<num;i++)
    if(num%i==0)
      return false;
  return true;
}
void dfs(int t){

  //如果输入的数是奇数,则不可能实现两两相加
  if(n & 1){

    return;
  }
  // cout << t << " " << a[t] << endl;

  //递归到第n+1层,则意味递归完了所有数
  if(t == n+1){
    if(prime(a[1]+a[n])){
      output();
    }
  }
  else{
    for(int i = 2;i <= n;i++){
      if(!vis[i] && prime(a[t-1]+i)){//如果符合两个数之和为素数且该数在之前没有访问过
        a[t] = i;
        vis[i] = true;
        dfs(t+1);

        //如果算法返回,进行回溯
        vis[i] = false;
      }
    }
  }
}

int main()
{
  int k = 1;
  while(cin >> n){

    //注意输出格式,否则过不了
    memset(vis,false,sizeof(vis));
    memset(a,0,sizeof(a));
    cout << "Case " << k << ":" << endl;
    k ++;
    a[1] = 1;
    vis[1] = true;
    dfs(2);//默认了从1开始,那么1为第一层,深搜则从第二层开始
    cout << endl;

  }
  return 0;
}

Prime Ring Problem

标签:

原文地址:http://www.cnblogs.com/2016zhanggang/p/5425945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!