L2-029 特立独行的幸福 (25 分)

按题意模拟就好了...咳咳。

\(vis\)数组判断每轮迭代至数字\(1\)的过程中是否出现过重复数字。

哈希表\(S\)存储迭代过程中产生的中间数字,以便最后输出答案时过滤掉依附于其他数字的幸福数。

const int N=1e4+10;
bool vis[N];
int l,r;
unordered_set<int> S;

bool isprime(int x)
{
    if(x<2) return false;
    for(int i=2;i*i<=x;i++)
        if(x % i == 0)
            return false;
    return true;
}

int main()
{
    cin>>l>>r;

    bool ok=false;
    vector<PII> ans;
    for(int i=l;i<=r;i++)
    {
        memset(vis,0,sizeof vis);
        int t=i,cnt=0;
        while(true)
        {
            cnt++;
            int res=0;
            vis[t]=true;
            while(t)
            {
                res+=(t%10)*(t%10);
                t/=10;
            }
            if(vis[res])
                break;
            else
                t=res;

            S.insert(res);

            if(res == 1)
            {
                if(isprime(i))
                    ans.pb({i,cnt*2});
                else
                    ans.pb({i,cnt});
                break;
            }
        }
    }

    for(auto t:ans)
        if(!S.count(t.fi))
            cout<<t.fi<<' '<<t.se<<endl;

    if(ans.size() == 0) puts("SAD");
    //system("pause");
    return 0;
}
posted @ 2021-04-20 17:18  Dazzling!  阅读(123)  评论(0编辑  收藏  举报