1.题目描述:点击打开链接
2.解题思路:本题是一道普通的模拟题,根据题意易知计算器显示的数将会出现循环,因为显示的n位数一共就有限种情况,而平方的次数是无限多的。所以不妨一个个的模拟,每次都看新得到的数是否以前出现过,如果出现过就跳出循环。但如何判断是否出现过呢?第一种方法是利用STL中的set,同时写一个Next函数求出下一个k值。下面一共给出三份不同的代码,来分别体会一下效率上的巨大差异。
3.代码:
(一,Next函数中使用string,stringstream)
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;
typedef long long LL;
int Next(int n, int k)
{
stringstream ss;
ss << (LL)k*k;//为了防止结果溢出,要转化为long long
string s = ss.str();
if (s.length() > n)s = s.substr(0, n);//结果太长,取前n位
int ans;
stringstream ss2(s);
ss2 >> ans;
return ans;
}
int main()
{
//freopen("t.txt", "r", stdin);
int T;
cin >> T;
while (T--)
{
int n, k;
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;
}
提交后OJ显示的结果如下:
(二,Next函数中把string,stringstream换位普通的char数组)
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;
typedef long long LL;
int buf[100];
int Next(int n, int k)
{
if (!k)return 0;
LL k2 = (LL)k*k;
int L = 0;
while (k2 > 0)
{
buf[L++] = k2 % 10;//低位在前,高位在后
k2 /= 10;
}
n = min(n, L);//取较小者
int ans = 0;
for (int i = 0; i < n; i++)
ans = ans * 10 + buf[--L];
return ans;
}
int main()
{
//freopen("t.txt", "r", stdin);
int T;
cin >> T;
while (T--)
{
int n, k;
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;
}
提交后OJ显示的结果如下:
(三,利用Floyed判圈算法)
(1)概述:该算法的原理很简单:如果A,B两个人赛跑,B的速度是A的两倍,那么当跑道是直线时,肯定B永远在A的前面;当跑道是圆形时,则B将慢慢地追上A,这便是Floyed判圈算法。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;
typedef long long LL;
int buf[100];
int Next(int n, int k)
{
if (!k)return 0;
LL k2 = (LL)k*k;
int L = 0;
while (k2 > 0)
{
buf[L++] = k2 % 10;//低位在前,高位在后
k2 /= 10;
}
n = min(n, L);
int ans = 0;
for (int i = 0; i < n; i++)
ans = ans * 10 + buf[--L];
return ans;
}
int main()
{
//freopen("t.txt", "r", stdin);
int T;
cin >> T;
while (T--)
{
int n, k;
cin >> n >> k;
set<int>s;
int ans = k;
int k1 = k, k2 = k;
do
{
k1 = Next(n, k1);//小孩A
k2 = Next(n, k2); if (k2 > ans)ans = k2;
k2 = Next(n, k2); if (k2 > ans)ans = k2;//小孩B,速度是A的两倍
} while (k1 != k2);//追上后停止
cout << ans << endl;
}
return 0;
}
提交后OJ显示的结果如下: