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

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

本题思路不难,关键在于对C++中set(集合)容器的操作

#include <iostream> 
#include <set>
using namespace std;
int main() {
	int n, x;
	cin >> n;
	set<int> s;
	for (int i = 0; i < n; i++) {
		cin >> x;
		s.insert(x);//用insert()插入数据
	}
	//用正向迭代器遍历集合中所有元素(升序)
	for (set<int>::iterator it = s.begin(); it != s.end(); ++it) {
		int x = *it;
		while (x != 1) {
			if (x % 2 == 0) {
				x /= 2;
			}
			else {
				x = (3 * x + 1) / 2;
			}
			//用find()寻找数据,并用erase()删除
			if (s.find(x) != s.end()) {
				s.erase(s.find(x));
			}
		}
	}
	//用反向迭代器遍历集合中所有元素(降序)
	set<int>::reverse_iterator it = s.rbegin();
	cout << *it;
	++it;
	for (; it != s.rend(); ++it) {
		cout << " " << *it;
	}
	cout << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值