点击查看题目
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <climits>
#include <cstdlib>
#include <ctime>
using namespace std;
char buff[20];
int next(int n,int k)
{
if(!k) return 0;
long long k2 = (long long ) k * k;
memset(buff,0,sizeof(buff));
sprintf(buff,"%lld",k2);
if(strlen(buff) < n) n = strlen(buff);
k2 = 0;
for(int i = 0; i < n;i++)
{
k2 = k2 *10 + buff[i] - '0';
}
return k2;
}
int main()
{
int t;
cin >> t;
while(t--)
{
int n,k;
scanf("%d%d",&n,&k);
int k1 = k;
int k2 = k;
int ans = 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);
printf("%d\n",ans);
}
return 0;
}
该题的重点不在于题目而是在于该题中才用的求循环节的(圈)的方法。该题中<pre name="code" class="cpp"><span style="white-space:pre"> </span>int k1 = k;
int k2 = k;
int ans = 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);
这一段中k1,k2均是从k出发,每次但是每次求得时候k2 总是更新两次但是k1每次都是执行一次。这样的话就如果k1能追上k2的时候说明这中间有圈。就好像两个人在一个跑道上跑,一个人的速度是另外一个人的两倍,如果两个人相遇啦那就说明跑道有圈