1005 继续(3n+1)猜想 (25分)(不需排序)

1005 继续(3n+1)猜想 (25分)
首先说说自己的思路吧
也是用了三重循环比较复杂,时间空间复杂度较高,使用了vector向量以及迭代器。
n_1(函数)就是求该数字的卡拉兹(Callatz)猜想的数列(不包括本身)然后返回一个vector向量。
对存输入的数字的a向量进行备份存为b,之后进入循环,对b中的数字求得卡拉兹(Callatz)猜想的数列然后使用迭代器,之后在a向量中进行寻找,如果a中与得到的卡拉兹(Callatz)猜想的数列有相同的数字,在a中进行删除操作(迭代器完成)完成循环后,a中剩下满足条件的数字,用sort进行排序,输出。

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> n_1(int x) {
	vector<int>m;
	while (x != 1) {
		if (x % 2 != 0) {
			x = (3 * x + 1) / 2;
			m.push_back(x);
		}
		else {
			x /= 2;
			m.push_back(x);
		}
	}
	return m;
}
bool cmp(int a, int b) {
	return a > b;
}
int main() {
	int n, i, j, k;
	vector<int>a;
	cin >> n;
	for (i = 0; i < n; i++) {
		cin >> k;
		a.push_back(k);
	}
	vector<int>b = a;
	for (i = 0; i < b.size(); i++) {
		vector<int>p = n_1(b[i]);
		for (vector<int>::iterator iter = p.begin(); iter != p.end(); iter++) {
			for (vector<int>::iterator it = a.begin(); it != a.end();) {
				if (*iter == *it) {
					a.erase(it);
				}
				else {
					it++;
				}
			}
		}
	}
	sort(a.begin(), a.end(), cmp);
	for (i = 0; i < a.size(); i++) {
		if (i != 0) {
			cout << " ";
		}
		cout << a[i] ;
	}
	return 0;
}

第二种思路也是大家经常用的利用一个标记数组检测某个数是否被覆盖过该方法不用排序(优势),细节就是(如果你想节省空间),求出最大值mx,将该标记数组开mx个,并且在赋初值的时候也是细节,因为我们总体的思路是是将标记数组为0(没有被覆盖过)进行输出,但有一个问题就是该数组的的无关数字,举例子来说,给出的例子int n,int *a = new int[n];
6
3 5 6 7 8 11
开一个数字p[11]已经足够(在计算中只需处理小于最大值的数据)经过计算得到对应的十一个空间中的数据分别为
0 6 6 1 6 4 0 0 5 0 2 1
因此第九位数据与我们的判断条件有冲突,所以我们在最初设置数组初始值的时候,先将数组全部设置为1,然后将pa[[i]]设置为0,这样以来直接抛弃不是输入数据中的数字。然后附上代码。(在提交的时候发现C语言比c++时间更短,空间更小)

#include<stdio.h>
#include<stdlib.h>
int n_max(int* a, int n) {
	int mx = 0;
	for (int i = 0; i < n; i++) {
		if (a[i] > mx) {
			mx = a[i];
		}
	}
	return mx;
}
int main() {
	int n, i;
	scanf("%d", &n);
	int *a = (int *)malloc(sizeof(int) * n);
	for (i = 0; i < n; i++) {
		scanf("%d", &a[i]);
	}
	int mx = n_max(a, n);
	int *p = (int *)malloc(sizeof(int) * mx + 1);
	for (i = 0; i <= mx; i++) {
		p[i] = 1;
	}
	for (i = 0; i < n; i++) {
		p[a[i]] = 0;
	}
	for (i = 0; i < n; i++) {
		while (a[i] != 1) {
			if (a[i] & 1) {
				a[i] = (a[i] * 3 + 1) / 2;
				if (a[i] <= mx) {
					p[a[i]]++;
				}
			}
			else {
				a[i] /= 2;
				if (a[i] <= mx) {
					p[a[i]]++;
				}
			}
		}
	}
	int cnt = 0;
	for (i = mx; i > 0; i--) {
		if (cnt != 0 && p[i] == 0) {
			printf(" ");
		}
		if (p[i] == 0) {
			printf("%d", i);
			cnt++;
		}
	}
}

欢迎各位查漏补缺,指正批评!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值