每周一题之1 3n+1问题
PC/UVa IDs: 110101/100
Popularity: A
Success rate: low Level: 1
测试地址:
https://vjudge.net/problem/UVA-100
[问题描述]
考虑如下的序列生成算法:从整数 n 开始,如果 n 是偶数,把它除以 2;如果 n 是奇数,把它乘 3 加1。用新得到的值重复上述步骤,直到 n = 1 时停止。例如,n = 22 时该算法生成的序列是:
22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1
人们猜想(没有得到证明)对于任意整数 n,该算法总能终止于 n = 1。这个猜想对于至少 1 000 000内的整数都是正确的。
对于给定的 n,该序列的元素(包括 1)个数被称为 n 的循环节长度。在上述例子中,22 的循环节长度为 16。输入两个数 i 和 j,你的任务是计算 i 到 j(包含 i 和 j)之间的整数中,循环节长度的最大值。
[输入]
输入每行包含两个整数 i 和 j。所有整数大于 0,小于 1 000 000。
[输出]
对于每对整数 i 和 j,按原来的顺序输出 i 和 j,然后输出二者之间的整数中的最大循环节长度。这三个整数应该用单个空格隔开,且在同一行输出。对于读入的每一组数据,在输出中应位于单独的一行。
[样例输入]
1 10
100 200
201 210
900 1000
[样例输出]
1 10 20
100 200 125
201 210 89
900 1000 174
注意题目中没有说 也没有告诉 给出的两个数 是按从小到大的顺序给出的 所以我们要长个心眼 不然根本不能编译通过
错解1:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
int arr[10000000];
bool cmp(int a,int b){
return a > b;
}
void fun(int a,int b){
int k = 0,temp = 0,j = 0;
memset(arr,0,sizeof(arr));
for(int i = a;i <= b;i++){
k = i;
temp = 0;
while(k != 1){
if(k == 1){
break;
}
if(k % 2 == 0){
k = k / 2;
}else{
k = k * 3 + 1;
}
temp++;
}
arr[j++] = temp + 1;
}
sort(arr,arr + j,cmp);
}
int main(){
long long n,m,l = 0;
while(~scanf("%lld%lld",&n,&m)){
fun(n,m);
cout << n << " " << m << " " << arr[0] << endl;
}
return 0;
}
解题思路:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
int maxx;
void fun(int a,int b){
int k,temp;
maxx = 0;
for(int i = min(a, b);i <= max(a, b);i++){
k = i;
temp = 1;
while(k != 1){
if(k % 2 == 0){
k = k / 2;
}else{
k = k * 3 + 1;
}
temp++;
}
maxx = max(temp,maxx);
}
}
int main(){
long long n,m,l = 0;
while(~scanf("%lld%lld",&n,&m)){
fun(n,m);
cout << n << " " << m << " " << maxx << endl;
}
return 0;
}
每周一题之2 Mineweep(扫雷)
Minesweeper (扫雷)
PC/UVa IDs: 110102/10189,
Popularity: A,
Success rate: high Level: 1
测试地址:https://vjudge.net/problem/UVA-10189
[问题描述]
Have you ever played Minesweeper? It’s a cute little game which comes within a certain Operating
System which name we can’t really remember. Well, the goal of the game is to find where are all the mines within a M × N field. To help you, the game shows a number in a square which tells you how many mines there are adjacent to that square. For instance, supose the following 4 × 4 field with 2 mines (which are represented by an ‘*’ character):
*…
…
.*…
…
If we would represent the same field placing t