【来源】
1005. 继续(3n+1)猜想 (25)
【分析】这道题需要费些脑筋。
博主的思路如下:
题目要求按照从大到小的顺序输出关键字。首先假定所有数都为“关键数”。然后依次遍历整个数组。若该数为“关键数”,则计算从这个数经过(3n+1)猜想到1的过程中得到的数,若某个数之前被判定为“关键数”,则取消这个数的“关键书”属性。遍历完数组之后,真正的“关键数”便会被筛选出来。最后把“关键数”排序输出即可。
【源码】
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
int main()
{
int n;
cin >> n;
int* nums = new int[n];
for (int i = 0; i < n; ++i){
cin >> nums[i];
}
bool* keys = new bool[n];
memset(keys, true, n*sizeof(bool));
for (int i = 0; i < n; ++i){
if (keys[i]){
int number = nums[i];
while (number != 1){
if (number % 2 == 0){
number /= 2;
}
else{
number = (3 * number + 1)/2;
}
for (int i = 0; i < n; ++i){
if (number == nums[i] && keys[i] == true){
keys[i] = false;
break;
}
}
}
}
}
vector<int> realkeys;
for (int i = 0; i < n; ++i){
if (keys[i]){
realkeys.push_back(nums[i]);
}
}
sort(realkeys.rbegin(), realkeys.rend());
cout << realkeys[0];
for (int i = 1; i < realkeys.size(); ++i){
cout << " " << realkeys[i];
}
delete[] keys;
delete[] nums;
system("pause");
return 0;
}
【点评】
博主采用的算法复杂度大概为O(N^3),如果有更好的算法,欢迎留言讨论。