uva 11549 CALCULATOR CONUNDRUM

简介: 题目链接刘汝佳算法竞赛经典入门训练指南p42

题目链接

刘汝佳算法竞赛经典入门训练指南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;
}

代码2:

#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;
}

代码3(Floyd判圈法):

#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;
}
目录
相关文章
UVa11549 - Calculator Conundrum (Floyd判圈法)
UVa11549 - Calculator Conundrum (Floyd判圈法)
55 0
|
存储
LeetCode 227. Basic Calculator II
实现一个基本的计算器来计算一个简单的字符串表达式的值。 字符串表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格 。 整数除法仅保留整数部分。
56 0
LeetCode 227. Basic Calculator II
HDU-1012,u Calculate e
HDU-1012,u Calculate e
|
C++
蓝桥杯 - C++ calculation
蓝桥杯 - C++ calculation
157 0
|
Java Go
HDU 1012 u Calculate e【暴力打表,水】
u Calculate e Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 46844    Accepted Submission(s)...
1017 0