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

题目链接

  1. 题意很好理解,在给定的这一系列数字进行卡拉兹猜想的过程中会产生一些数字已经验证过了的情况。
  2. 我们的目标就是找出最少需要验证的数字。
  3. 先创建一个字典key值就是给定的一系列数,value初始全都为0,表示都需要进行验证。
  4. 从给定第一个数开始验证,产生的中间数据如果在字典中,将对应的value置1,说明这个数不用再验证了。
  5. 最后将字典在遍历一次等于0的就是我们需要的结果,对其进行从大到小的排序。

C++ 代码

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

int main() {
	map<int, int> m;
	vector<int> res;
	int n;
	int temp;
	cin >> n;
	while (n--) {
		cin >> temp;
		m[temp] = 0;
	}
	for (auto it = m.begin(); it != m.end(); it++) {
		temp = it->first;
		while (temp != 1) {
			if (temp % 2 == 0)
				temp = temp / 2;
			else
				temp = (3 * temp + 1) / 2;
			if (m.count(temp) == 1)
				m[temp] = 1;
		}
	}
	for (auto it = m.begin(); it != m.end(); it++) {
		if (it->second == 0)
			res.push_back(it->first);
	}
	reverse(res.begin(), res.end());
	cout << res[0];
	for (int i = 1; i < res.size(); i++) {
		cout << " " << res[i];
	}
	cout << endl;
	return 0;
}
复制代码

python3代码

def main():
    n = input()
    num_str = input().split(' ')
    res={}
    result =[]
    for i in num_str:
        if(int(i) not in res.keys()):
            res[int(i)] = 0

    for i in num_str:
        i = int(i)
        while i !=1:
            if(i%2==0):
                i = i/2
            else:
                i = (3*i+1)/2

            if(i in res.keys()):
                res[i] = 1

    for i in res:
        if(res[i] == 0):
            result.append(i)

    result.sort(reverse=True)
    for  i ,value in enumerate(result):
        if(i!=0):
            print(" ",end='')
        print(value,end='')

main()
复制代码

转载于:https://juejin.im/post/5ce391b4f265da1bab298294

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值