UVA 3n+1problem
来源:互联网 发布:中海达手簿软件 编辑:程序博客网 时间:2024/05/22 03:51
手速:点击打开链接
一开始是大表看是否有规律,但是很遗憾没有
又想把所以的结果存在数组为1000000的内,很遗憾很慢
其实直接求……
#include<cstdlib>#include<cstdio>#include<algorithm>#include<cstring>#include<iostream>using namespace std;int hash[1000001];void solve(int n){ int i,re=1,nn=n; if(hash[n]!=-1) return; while(n!=1) { if(n%2) n=n*3+1; else n/=2; re++; } hash[nn] =re;}int maxi(int i,int j){ int ans=-1; for(int k=i;k<=j;k++) { if(hash[k]>ans)ans=hash[k]; }return ans;}int main(){ int i,j,k,flag; memset(hash,-1,sizeof(hash)); while(scanf("%d%d",&i,&j)!=EOF) { flag=0; if(i>j) {swap(i,j);flag=1;} for(k=i;k<=j;k++) { solve(k); } int ans= maxi(i,j); if(flag) printf("%d %d %d\n",j,i,ans); else printf("%d %d %d\n",i,j,ans); } return 0;}
或者将结果都存储在数组中(记忆化)
#include<cstdlib>#include<cstdio>#include<algorithm>#include<cstring>#include<iostream>using namespace std;int hash[1000002];void solve(int n){ int i,re=1,nn=n; while(n>1)//写n!=1就死循环了 { if(n<1000000&&hash[n]!=-1) {re+=hash[n]-1;break;} if(n&1) n=n*3+1; else n/=2; re++; } hash[nn] =re;}int maxi(int i,int j){ int ans=-1; if(i>j) swap(i,j); for(int k=i;k<=j;k++) { if(hash[k]>ans)ans=hash[k]; }return ans;}int main(){ int i,j,k; memset(hash,-1,sizeof(hash)); for(k=1;k<1000000;k++) solve(k); while(scanf("%d%d",&i,&j)!=EOF) { int ans= maxi(i,j); printf("%d %d %d\n",i,j,ans); } return 0;}
0 0
- UVA 3n+1problem
- ACM UVa problem 3n+1
- Uva 694 The 3n + 1 problem
- UVA 100 The 3n + 1 problem
- UVa 100 - The 3n + 1 problem
- UVa 100 - The 3n + 1 problem
- UVa 100 - The 3n + 1 problem
- Uva 100 3n+1problem
- uva 100 The 3n+1 problem
- UVa 100 - The 3n + 1 problem
- UVa 100 The 3n + 1 problem
- uva 100 The 3n + 1 problem
- UVa 100 The 3n + 1 problem
- UVA: The 3n + 1 problem
- UVa - The 3n + 1 problem 题解
- UVa 100 The 3n + 1 problem
- uva--100 - The 3n + 1 problem
- UVa 100 - The 3n + 1 problem
- 全国地区名字典
- 互联网系统架构的演进
- 《实时碰撞检测算法技术》读书笔记(一):包围体(BV)
- Arm-Linux 编译Asterisk
- Asp.net MVC2学习笔记3-View
- UVA 3n+1problem
- 可伸缩Web架构与分布式系统(1)
- 浅析数据分层存储的又一层
- 可伸缩Web架构与分布式系统(2)
- NYOJ 187 快速查找素数
- 情人节
- TCP协议疑难杂症全景解析
- linux 解压命令大全
- android sqlite *.db-journal