UVA-11549(floyd判圈算法)

题意:

给一个整数k,每次平方后只能显示结果的前n位,问在这个过程中能得到的最大的数是多少;

思路:

floyd判圈算法;它的正确性建立在这得到的这些数是有限的,所以一定是一个循环,在这个循环的圈里面,一个快一个慢,同时出发最后一定会再次相遇,此时结束;

在这个过程中得到最大值;

AC代码:

#include <bits/stdc++.h>
/*
#include <vector>
#include <iostream>
#include <queue>
#include <cmath>
#include <map>
#include <cstring>
#include <algorithm>
#include <cstdio>
*/
using namespace std;
#define For(i,j,n) for(int i=j;i<=n;i++)
#define Riep(n) for(int i=1;i<=n;i++)
#define Riop(n) for(int i=0;i<n;i++)
#define Rjep(n) for(int j=1;j<=n;j++)
#define Rjop(n) for(int j=0;j<n;j++)
#define mst(ss,b) memset(ss,b,sizeof(ss));
typedef  long long LL;
template<class T> void read(T&num) {
    char CH; bool F=false;
    for(CH=getchar();CH<'0'||CH>'9';F= CH=='-',CH=getchar());
    for(num=0;CH>='0'&&CH<='9';num=num*10+CH-'0',CH=getchar());
    F && (num=-num);
}
int stk[70], tp;
template<class T> inline void print(T p) {
    if(!p) { puts("0"); return; }
    while(p) stk[++ tp] = p%10, p/=10;
    while(tp) putchar(stk[tp--] + '0');
    putchar('
');
}

const LL mod=1e9+7;
const double PI=acos(-1.0);
const LL inf=1e18;
const int N=1e5+10;
const int maxn=1005;
const double eps=1e-10;

LL n;
LL k;
int a[30],cnt;
LL getnext(LL x)
{
    cnt=0;
    x=x*x;
    while(x)
    {
        a[++cnt]=x%10;
        x/=10;
    }
    LL s=0;
    for(int i=cnt;i>cnt-n&&i>0;i--)
    {
        s=s*10+a[i];
    }
    return s;
}

int main()
{
        int t;
        read(t);
        while(t--)
        {
            read(n);read(k);
            LL ans=k;
            LL k1=k,k2=k;
            while(1)
            {
                k1=getnext(k1);
                ans=max(ans,k1);
                k2=getnext(k2);
                ans=max(ans,k2);
                k2=getnext(k2);
                ans=max(ans,k2);
                if(k1==k2)break;
                //cout<<k1<<" "<<k2<<endl;
            }
            cout<<ans<<"
";

        }
        return 0;
}
原文地址:https://www.cnblogs.com/zhangchengc919/p/5662543.html