1005 继续(3n+1)猜想 (25分)
卡拉兹(Callatz)猜想已经在1001中给出了描述。在这个题目里,情况稍微有些复杂。
当我们验证卡拉兹猜想的时候,为了避免重复计算,可以记录下递推过程中遇到的每一个数。例如对 n=3 进行验证的时候,我们需要计算 3、5、8、4、2、1,则当我们对 n=5、8、4、2 进行验证的时候,就可以直接判定卡拉兹猜想的真伪,而不需要重复计算,因为这 4 个数已经在验证3的时候遇到过了,我们称 5、8、4、2 是被 3“覆盖”的数。我们称一个数列中的某个数 n 为“关键数”,如果 n 不能被数列中的其他数字所覆盖。
现在给定一系列待验证的数字,我们只需要验证其中的几个关键数,就可以不必再重复验证余下的数字。你的任务就是找出这些关键数字,并按从大到小的顺序输出它们。
输入格式:
每个测试输入包含 1 个测试用例,第 1 行给出一个正整数 K (<100),第 2 行给出 K 个互不相同的待验证的正整数 n (1<n≤100)的值,数字间用空格隔开。
输出格式:
每个测试用例的输出占一行,按从大到小的顺序输出关键数字。数字间用 1 个空格隔开,但一行中最后一个数字后没有空格。
输入样例:
6
3 5 6 7 8 11
输出样例:
7 6
作者
CHEN, Yue
单位
浙江大学
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
思路
这就好比去点灯与熄灯,输入了n个数之后,你面前有n个数,就是n栈点亮的灯,每次你用下寻函数去向下迭代查找该数所覆盖的数的时候,如果包括了你面前的初始输入的数,就将你面前的数的对应的灯熄灭掉,最后从后向前,输出还没有被熄灭的灯。
数组实现:
#include <iostream>
using namespace std;
void find (int n, int table[])
{
if (n == 1) return;
if(n % 2 == 0)
{
if (n/2 <= 100)
table[n/2] = 0;
find(n / 2, table);
}
else {
if ((3 * n + 1)/2 <= 100)
table[(3 * n + 1)/2] = 0;
find((3 * n + 1) / 2, table);
}
}
int main(){
int table[101];
for (int i = 0; i < 101; ++i) {
table[i] = 0;
}
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; ++i) {
cin >> a[i];
table[a[i]] = 1;
}
for (int i = 0; i < n; ++i) {
find(a[i],table);
}
bool t = false;
for (int i = 100; i > 0; --i) {
if (table[i] == 1)
{
if (t) cout << " " << i;
else{
t = true;
cout << i;
}
}
}
return 0;
}
Map实现:
#include <iostream>
#include <map>
using namespace std;
void find(int n, map<int,int> &mymap){
if(n == 1) return;
if(n % 2 == 0)
{
map<int, int>::iterator it = mymap.find(n/2);
if (it != mymap.end()) mymap[n/2] = 0;
find(n/2,mymap);
}
else{
map<int, int>::iterator it = mymap.find((3 * n + 1) / 2);
if (it != mymap.end()) mymap[(3 * n + 1) / 2] = 0;
find((3 * n + 1) / 2, mymap);
}
}
int main(){
map<int ,int> mymap;
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; ++i) {
cin >> a[i];
mymap[a[i]] = 1;
}
for (int i = 0; i < n; ++i) {
find(a[i],mymap);
}
bool t = false;
//这里使用倒叙迭代器
for (map<int,int>::reverse_iterator it = mymap.rbegin(); it != mymap.rend() ; it ++) {
if (it->second == 1)
{
if (t) cout << " " << it->first;
else{
cout << it->first;
t = true;
}
}
}
return 0;
}