您的位置:首页 > 其它

PAT乙级.1005. 继续(3n+1)猜想 (25)

2016-09-04 00:06 441 查看

1005. 继续(3n+1)猜想 (25)

题目

卡拉兹(Callatz)猜想已经在1001中给出了描述。在这个题目里,情况稍微有些复杂。

当我们验证卡拉兹猜想的时候,为了避免重复计算,可以记录下递推过程中遇到的每一个数。例如对n=3进行验证的时候,我们需要计算3、5、8、4、2、1,则当我们对n=5、8、4、2进行验证的时候,就可以直接判定卡拉兹猜想的真伪,而不需要重复计算,因为这4个数已经在验证3的时候遇到过了,我们称5、8、4、2是被3“覆盖”的数。我们称一个数列中的某个数n为“关键数”,如果n不能被数列中的其他数字所覆盖。

现在给定一系列待验证的数字,我们只需要验证其中的几个关键数,就可以不必再重复验证余下的数字。你的任务就是找出这些关键数字,并按从大到小的顺序输出它们。

输入格式

每个测试输入包含1个测试用例,第1行给出一个正整数K(<100),第2行给出K个互不相同的待验证的正整数n(1

思路

3n+1猜想:偶数乘以1/2,奇数求(3n+1)再乘1/2

每次变化时候,将覆盖的数在HashTable中标记出来

代码

version1.0

/**
* @tag     PAT_B_1005
* @authors R11happy (xushuai100@126.com)
* @date    2016-9-3 21:52-22:26
* @version 1.0
* @Language C++
* @Ranking  645/804
* @function null
*/

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;

int HashTable[10010];   //一开始开到110,俩段错误
int input[110];
//按从大到小排序
bool cmp(int a, int b)
{
return a>b;
}

int main(int argc, char const *argv[])
{
int i,j,t,K;
scanf("%d", &K);
for(i = 0; i < K; i++)
{
scanf("%d", &t);
input[i] = t;
while(t != 1)
{

if(t % 2 == 0)  t/=2;
else    t = (3*t+1)/2;
HashTable[t] = 1;   //这里,t的值有可能很大,所以HashTable要开大一点
}
}
sort(input, input+K, cmp);
for(j = 0; j<K; j++)
{
if(HashTable[input[j]] == 0)
{
printf("%d",input[j] );
break;
}
}
for(j++; j<K; j++)
{
if(HashTable[input[j]] == 0)
{
printf(" %d",input[j] );
}
}
return 0;
}


version2.0

/**
* @tag     PAT_B_1005
* @authors R11happy (xushuai100@126.com)
* @date    2016-9-3 21:52-22:26
* @version 1.0
* @Language C++
* @Ranking  null
* @function null
*/

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;

int HashTable[110];
int input[110];
bool cmp(int a, int b)
{
return a>b;
}

int main(int argc, char const *argv[])
{
int i, j, t, K;
scanf("%d", &K);
for (i = 0; i < K; i++)
{
scanf("%d", &t);
input[i] = t;
while (t != 1)
{

if (t % 2 == 0) t /= 2;
else    t = (3 * t + 1) / 2;
if (t > 100)    continue;
HashTable[t] = 1;
}
}
//从大到小排序
sort(input, input + K, cmp);
for (j = 0; j<K; j++)
{
if (HashTable[input[j]] == 0)
{
printf("%d", input[j]);
break;
}
}
for (j++; j<K; j++)
{
if (HashTable[input[j]] == 0)
{
printf(" %d", input[j]);
}
}
return 0;
}


收获

虽然数不超过100,但在求覆盖的数时候,由于要做3n+1。所有可能会超出100,不处理的话,在最后两个测试点会出现段错误。解决方法:

1.version1.0的做法简单粗暴:直接将数组开到10010

2.version2.0的做法是,当出现超过100的数时候,直接continue

while (t != 1)
{

if (t % 2 == 0) t /= 2;
else    t = (3 * t + 1) / 2;
if (t > 100)    continue;
HashTable[t] = 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: