uva 11549 CALCULATOR CONUNDRUM

举报
xindoo 发表于 2022/04/16 00:12:06 2022/04/16
992 0 0
【摘要】 题目链接 刘汝佳算法竞赛经典入门训练指南p42 代码1: #include <set> #include <iostream> #include <sstream> using namespace std; int next(int n, int k) { stringstream ...

题目链接

刘汝佳算法竞赛经典入门训练指南p42

代码1:

#include <set>
#include <iostream>
#include <sstream>
using namespace std;

int next(int n, int k)
{
    stringstream ss;
    ss <<(long long)k*k;
    string s = ss.str();
    if (s.length() > n)
        s = s.substr(0, n);
    int ans = 0;
    stringstream ss2(s);
    ss2 >> ans;
    return ans;
}

int main()
{
    int t;
    int n, k;
    cin>>t;
    while (t--)
    {
        cin>>n>>k;
        set<int> s;
        int ans = k;
        while (!s.count(k))
        {
            s.insert(k);
            if (k > ans)
                ans = k;
            k = next(n, k);
        }
        cout << ans << endl;
    }
    return 0;
}

#include <set>
#include <iostream>
#include <sstream>
using namespace std;

int next(int n, int k)
{
    int buf[10];
    if (!k)
        return 0;
    long long k2 = (long long)k*k;
    int l = 0;
    while (k2 > 0)
    {
        buf[l++] = k2%10; k2 /= 10;
    }
    if (n > l)
        n = l;
    int ans = 0;
    for (int i = 0; i < n; i++)
        ans = ans*10 + buf[--l];
    return ans;
}

int main()
{
    int t;
    int n, k;
    cin>>t;
    while (t--)
    {
        cin>>n>>k;
        set<int> s;
        int ans = k;
        while (!s.count(k))
        {
            s.insert(k);
            if (k > ans)
                ans = k;
            k = next(n, k);
        }
        cout << ans << endl;
    }
    return 0;
}

#include <set>
#include <iostream>
#include <sstream>
using namespace std;
int buf[10];
int next(int n, int k)
{
    if (!k)
        return 0;
    long long k2 = (long long)k*k;
    int l = 0;
    while (k2 > 0)
    {
        buf[l++] = k2%10; k2 /= 10;
    }
    if (n > l)
        n = l;
    int ans = 0;
    for (int i = 0; i < n; i++)
        ans = ans*10 + buf[--l];
    return ans;
}

int main()
{
    int t;
    int n, k;
    cin>>t;
    while (t--)
    {
        cin>>n>>k;
        int ans = k;
        int k1 = k, k2 = k;
        do
        {
            k1 = next(n, k1);
            k2 = next(n, k2);
            if (k2 < ans)
                ans = k2;
            k2 = next(n, k2);
            if (k2 < ans)
                ans = k2;
        }while (k1 != k2);
        cout << ans << endl;
    }
    return 0;
}



文章来源: xindoo.blog.csdn.net,作者:xindoo,版权归原作者所有,如需转载,请联系作者。

原文链接:xindoo.blog.csdn.net/article/details/8949187

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。