[PAT乙] 1005. 继续(3n+1)猜想 (25)

来源:互联网 发布:山西软件开发公司 编辑:程序博客网 时间:2024/05/17 08:02

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

#include <iostream>#include <string>#include <vector>#include <algorithm>#include <set>using namespace std;vector<string> create(int a) {    vector<string> s;    //int dight;    while (a>1) {        //奇数        if (a & 1) {            a = (3 * a + 1) / 2;            s.push_back(to_string(a));        }        else {            a /= 2;            s.push_back(to_string(a));        }    }    return s;}int main(){    int num, input;    vector<vector<string> > vs;    vector<int> vn;    cin >> num;    vector<bool> mark(num, false);    for (int i = 0; i<num; ++i) {        cin >> input;        vn.push_back(input);        vs.push_back(create(input));    }    for (int i = 0; i<num; ++i) {        for (int j = 0; j<num; ++j) {            if (i == j) continue;            if (find(vs[j].begin() ,vs[j].end(),to_string(vn[i])) != vs[j].end())                mark[i] = true;        }    }    set<int, greater<int> > record;    for (int i = 0; i<num; ++i) {        if (!mark[i]) {            record.insert(vn[i]);        }    }    int tag = 0;    for(auto it=record.cbegin(); it!=record.cend(); ++it) {        if(!tag) tag=1;        else cout<<' ';        cout<< *it;    }    return 0;}

时间大概2-3ms


下面贴柳婼女神的代码,比我简单多了= =

#include <iostream>#include <algorithm>using namespace std;int cmp(int a, int b) {return a > b;}int main() {    int n;    cin >> n;    int *a = new int [n];    for (int i = 0; i < n; i++) {        cin >> a[i];    }    int t;    sort(a, a + n, cmp);    for (int i = 0; i < n; i++) {        t = a[i];        while (t != 1 && t != 999) {            if (t % 2 == 0) {                t = t / 2;            } else {                t = (t * 3 + 1) / 2;            }            for (int j = 0; j < n; j++) {                if(t == a[j] && j != i)                    a[j] = 999;//相同的数字变为999            }        }    }    sort(a, a + n, cmp);//999排序后到了最前面    int temp = 0;    for (int k = n - 1; k >= 0; k--) {        if (a[k] != 999)//第一个不等于999的下标为temp            temp = k;    }    for (int m = temp; m < n - 1; m++) {        cout << a[m] << " ";    }    cout << a[n - 1];    delete [] a;    return 0;}
原创粉丝点击