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

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

本质是对输入数列进行检索,对前面的数进行3n+1计算产生的中间量进行记录,在后面遇到某个数等于该中间量时,可认为该数被覆盖了。 若遍历数列结束,出现了有的数不能被覆盖,则该数为关键树

// PAT 1005 乙级.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;

map<int, int> m;

bool cmp(int x, int y) {
    return x > y;
}
void callatz(int a) {
    while (a != 1) {
        if (a % 2 == 0) {
            a /= 2;                    
        }
        else
        {
            a = (3 * a + 1) / 2;
        }
        if (m.count(a)) break;
        //cout << a << endl;
        m[a]++;      
    }
}

int main()
{
    int n, temp, flag = 0;
    vector<int> res;
    cin >> n;
    cin >> temp;
    res.push_back(temp);
    callatz(temp);
    for (int i = 1; i < n; i++) {
        cin >> temp;
        res.push_back(temp);
        if (!m.count(temp)) {    
            callatz(temp);
        }
    }
    sort(res.begin(), res.end(), cmp);
    int i;
  
    for (i = 0; i < res.size(); i++) {
        if (!m.count(res[i])) {
            if (flag == 1) cout << " ";
            cout << res[i];
            flag = 1;
        }
    }
       
    return 0;
}

为了从大到小输出,使用#include中的sort()。

bool cmp(int x, int y) {
    return x > y;
}
sort(res.begin(), res.end(), cmp);

在计算3n+1的过程中,可能会出现n>100的情况,直接使用vector<>动态地为容器添加元素即可,不用担心越界

对于按空格隔开输出,最后一个后面不跟空格的套路

 for (i = 0; i < res.size(); i++) {
        if (!m.count(res[i])) {
            if (flag == 1) cout << " ";
            cout << res[i];
            flag = 1;
        }
    }

第一次输出时 flag = 0,不输出空格,此后每个都输出空格+数据,直到最后一个

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值