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

HDU 1010 Prime Ring Problem

时间:2017-08-10 01:15:37      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:row   splay   phi   tin   ret   clock   不能   简单   problem   

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.

 

思路就是简单的一个一个试,回溯即可。

不过这题输出判定很恶心,注意末尾不能有多余的空格,否则会PE

技术分享
#include <iostream>
#include <cmath>
#include <algorithm>

using namespace std;

int prime[] = {3,5,7,11,13,17,19,23,29,31,33,37};
bool isprime(int x){
  for (int i=0;i<12;i++){
    if (prime[i] == x){
      return true;
    }
  }
  return false;
}
int visited[100] = {0},res[100] = {0};
int n;
void tryit(int now){
  // for (int i=1;i<=n;i++){
  //   cout << res[i] << " ";
  // } cout << now << endl;
  if (now == n){
    if (!isprime(res[1] + res[now])) return;
    cout << 1;
    for (int i=2;i<=n;i++){
      cout << " " << res[i];
    }
    cout << endl;
    return ;
  }
  if (now == 0){
    res[1] = 1; visited[1] = 1;
    tryit(1);
    return;
  }
  int index = upper_bound(prime,prime+12,res[now]) - prime;
  for (int i=index;i<12 && prime[i] <= 2*n;i++){
    if (prime[i] <= res[now]) continue;
    int nownum = prime[i] - res[now];
    if (!visited[nownum] && nownum <= n){
      visited[nownum] = 1;
      res[now+1] = nownum;
      tryit(now+1);
      visited[nownum] = 0;
    }
  }

  return;
}
int main(){
  // freopen("test.in","r",stdin);
  // freopen("test.out","w",stdout);
  int total = 0;
  while (cin >> n){
    total ++;
    cout << "Case " << total << ":" << endl;
    tryit(0);
    cout << endl;
  }
  return 0;
}
View Code

 

HDU 1010 Prime Ring Problem

标签:row   splay   phi   tin   ret   clock   不能   简单   problem   

原文地址:http://www.cnblogs.com/ToTOrz/p/7336925.html

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