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;
}