Prime Ring Problem UVA
来源:互联网 发布:自由贸易的利弊 知乎 编辑:程序博客网 时间:2024/06/16 02:02
题目:输入n,输出1~n的素数环
分析:起初,我用的next_permutation,发现紫书上开始也是我这想法..暴力求解。提交上去超时了..看了题解,用的回溯法。比如 1 2 3 4 5 当发现(4+5=9非素数时) 不往下走了..这点省了很大的时间。
说明:穷举法,当n=16,16!..我之前没概念。。n=8答案秒出,n=16差不多等了一分钟都没有出答案...意识到了回溯法的重要性..
ps:uva怎么总是格式出错..还是不习惯uva的格式问题
#include <iostream>#include <math.h>#include <memory.h>using namespace std;int n,arr[20],cnt=0;bool vis[20]= {0};bool prime(int n){ if(n<3) return false ; int len=(int)sqrt(n+0.0); for (int i=2; i<=len; i++) { if(n%i==0) return false ; } return true;}void dfs(int cur){ if(cur==n&&prime(arr[n-1]+arr[0])) { for(int i=0; i<n; i++) if(!i) cout<<arr[i]; else cout<<" "<<arr[i]; cout<<endl; } else { for(int i=2; i<=n; i++) { if(!vis[i]&&prime(arr[cur-1]+i)) { arr[cur]=i; vis[i]=true; dfs(cur+1); vis[i]=false; } } }}int main(){ while(cin>>n) { if(cnt++) cout<<endl; cout<<"Case "<<cnt<<":"<<endl; arr[0]=1; memset(vis,0,sizeof(vis)); dfs(1); }}
0 0
- Prime Ring Problem UVA
- Prime Ring Problem UVA
- Prime Ring Problem UVA
- UVA 524 - Prime Ring Problem
- uva 524 - Prime Ring Problem
- uva 524 Prime Ring Problem
- UVa:524 Prime Ring Problem
- uva 524 - Prime Ring Problem
- UVa 524 - Prime Ring Problem
- uva 724 Prime Ring Problem
- UVA - 524 Prime Ring Problem
- UVa-524 - Prime Ring Problem
- UVA - 524 Prime Ring Problem
- UVa - 524 - Prime Ring Problem
- UVA - 524 Prime Ring Problem
- uva 524Prime Ring Problem
- uva 524 - Prime Ring Problem
- Prime Ring Problem(UVA 524)
- [联表] -- YII2 GridView联表:文本框搜索、下拉框选择搜索和排序
- 1107
- KVO改变textfield的placeholderLabel的属性
- LINUX下部署NFS
- Vim
- Prime Ring Problem UVA
- 2017-3月 java面试题总览
- 安卓开发:角标显示未读消息数
- CSS相对于屏幕上下居中定位写法
- ajxa异步传输文件
- gcc class driver
- apt-get install安装插件自动按Y和自动输入root密码
- 常用的Mysql数据库操作语句大全
- 设计模式之适配器模式