HDOJ1016.Prime Ring Problem
2015-10-05 16:56
316 查看
试题请参见: http://acm.hdu.edu.cn/showproblem.php?pid=1016
Note: the number of first circle should always be 1.
![](http://acm.hdu.edu.cn/data/images/1016-1.gif)
PE. 输出结果的时候, 若是序列中的最后一个数字, 不需要在数字之后加空格.
题目概述
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.
![](http://acm.hdu.edu.cn/data/images/1016-1.gif)
解题思路
回溯. 生成以1作为第1个元素的全排列.遇到的问题
TLE. 于是想到了一个剪枝的方法, 如果当前的序列(如1 3)已经不能构成质数环(因为1 + 3 = 4不是质数), 则不要继续搜索.
PE. 输出结果的时候, 若是序列中的最后一个数字, 不需要在数字之后加空格.
源代码
#include <iostream> #include <cmath> bool isPrime(int x) { for ( int i = 2; i <= std::sqrt(x); ++ i ) { if ( x % i == 0 ) { return false; } } return true; } bool isPrimeLine(int* ring, int n) { for ( int i = 1; i < n; ++ i ) { if ( !isPrime(ring[i] + ring[i - 1]) ) { return false; } } return true; } bool isPrimeRing(int* ring, int n) { for (int i = 0; i < n; ++i) { if (!isPrime(ring[(i + n) % n] + ring[(i + n + 1) % n])) { return false; } } return true; } void getPrimeRing(int* ring, bool* isUsed, int selectedNumbers, int totalNumbers) { if ( selectedNumbers == totalNumbers ) { if ( isPrimeRing(ring, totalNumbers) ) { for ( int i = 0; i < totalNumbers; ++ i ) { std::cout << ring[i] << ( i == totalNumbers - 1 ? "\n" : " " ); } } } for ( int i = 1; i < totalNumbers; ++ i ) { if ( !isUsed[i] ) { isUsed[i] = true; ring[selectedNumbers] = i + 1; if ( isPrimeLine(ring, selectedNumbers + 1) ) { getPrimeRing(ring, isUsed, selectedNumbers + 1, totalNumbers); } isUsed[i] = false; } } } int main() { const int MAX_SIZE = 20; // Put number 1 as the first element bool isUsed[MAX_SIZE] = { 1, 0 }; int ring[MAX_SIZE] = { 1, 0 }; int n = 0, currentCase = 0; while ( std::cin >> n ) { std::cout << "Case " << ++ currentCase << ":" << std::endl; getPrimeRing(ring, isUsed, 1, n); std::cout << std::endl; } return 0; }
相关文章推荐
- 数据挖掘复习 回归2
- 开始学Java,
- 第4周、项目3(3)—单链表应用-递增
- 第3周项目4 顺序表应用问题(1)
- [237]Delete Node in a Linked List
- 第四周项目3--单链表应用(3)
- 想开网店?向你推荐最好的开源电子商务平台
- Ubuntu 14.04鼠标光标狂闪问题
- UVA 11027 - Palindromic Permutation
- pom.xml解析
- Android UI SurfaceView的使用-绘制组合图型,并使其移动
- 数据结构实践——猴子选大王
- 第四周【数据结构实践项目——链表 项目5 - 猴子选大王】
- xXx时间屏保3.6
- 第4周 项目3 - 单链表应用(1)
- 快速选择
- 第三周项目三 求集合并集
- 快速选择
- Android UI SurfaceView的使用-绘制组合图型,并使其移动
- (数据挖掘-入门-6)十折交叉验证和K近邻