杭电1016————素数环之DFS
来源:互联网 发布:淘宝优惠券领券链接 编辑:程序博客网 时间:2024/05/28 01:36
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 14061 Accepted Submission(s): 6390
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.
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.
You are to write a program that completes above process.
Print a blank line after each case.
Sample Input
68
Sample Output
Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2这个题目很容易想到搜索的办法,是属于比较简单的DFS题目,代码经过测试AC,但是时间用了大约500MS,亲测当n>=11时,这段代码卡顿。杭电的范围是0<n<20,目测是数据水了。杭电最快是15MS。#include <stdio.h>#include <string.h>#include <math.h>#define maxn 30int prime[maxn],vis[maxn];/*prime记录要输出的序列 vis表示当前数字是否已被使用*/ int n;/*the number*/void print(){for(int i = 0;i < n;i++){if(i != n-1)printf("%d ",prime[i]);elseprintf("%d\n",prime[i]);}}int isprime(int x){int flag = 1;for(int i = 2;i <= sqrt(x);i++){if(x % i == 0){flag = 0;break;}}return flag;}void DFS(int x,int count)/*x记录数字的值,count记录第几个数*/ {if( isprime(x+1) && count == n)/*终止条件,即递归出口*/ {print();return ;}else{for(int i = 2 ; i <= n; i++){if( isprime(i+x) && vis[i] == 0){vis[i] = 1;prime[count++] = i;DFS(i,count);count--;vis[i] = 0;}}}}int main(){int cases = 0;/*case x*/while(scanf("%d",&n) != EOF){cases++;memset(prime,0,sizeof(prime));memset(vis,0,sizeof(vis));prime[0] = 1;/*the begining number is always one*/vis[1] = 1;/*one has been used*/ printf("Case %d:\n",cases);DFS(1,1);printf("\n");} return 0;}
0 0
- 杭电1016————素数环之DFS
- 杭电ACM1501——Zipper~~DFS
- 杭电-1016Prime Ring Problem(素数打表+DFS)
- DFS之素数环
- 杭电1016 素数环
- 杭电ACM1431——素数回文~~打表法
- 杭电1015————DFS+字符串
- 杭电1175——连连看(DFS)
- 杭电1241——Oil Deposits(深搜dfs)
- 杭电acm 1016 素数环
- 杭电OJ——1164 Eddy's research I——素数筛选
- 杭电ACM_1016_素数环
- 杭电OJ1016 素数环
- hdu 1016 dfs(素数环)
- hdu 1016 dfs素数环
- 【dfs】hdu 1016 素数环
- 杭电1045————DFS简单难度题目
- 杭电OJ——1011 Starship Troopers(dfs + 树形dp)
- linux getsockopt与setsockopt设置缓冲区大小
- 浅谈三层
- 基础篇——序列化和文件的输入输出
- hdu2043 密码
- AFNetwork作用和用法详解
- 杭电1016————素数环之DFS
- 简单的翻页组件
- 使用Apache FtpServer搭建FTP服务器
- XML简介(章节摘要)
- 计数器模块
- 关于远程界面变全屏与远程服务器数据拷贝到本地的解决方案
- Android开源框架ImageLoader的完美例子
- Vi编辑器的使用方法
- julia: 如何序列化和反序列化?