uva11549 老式计算器 (Floyd判圈 )

用神奇的Floyd判圈算法。

如果两个小孩在直线跑道上跑同时出发,第二个小孩的速度是第一个小孩的两倍,那第二个小孩永远在前面。但如果在环形跑道上的话,第二个小孩将会“追上”第一个小孩。

/* ***********************************************
Author        :fisty
Created Time  :2014/12/21 22:38:24
File Name     :uva11549.cpp
************************************************ */

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
typedef long long ll;
#define MAX_N 1000000000

int next(int n, int k){
    //获取k*2 并且把前n位返回
    if(!k) return 0;
    int ans = 0, L = 0;
    char buf[10];
    ll kk = (ll)k*(ll)k;      //kk为 k^2
    //借助数组获取前n位
    while(kk > 0){
        buf[L++] = kk % 10;
        kk /= 10;
    }
    if(n > L) n = L;
    for(int i = 0;i < n; i++){
        ans = buf[--L] + ans*10;
    }
    return ans;
}
int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    cin.tie(0);
    std::ios::sync_with_stdio(false);
    int t;
    cin >> t;
    while(t--){
        int n, k;
        cin >> n >> k;
        int k1 = k, k2 = k;
        int ans = k;
        do{
            //Floyd判圈
            //k2的速度为k1的2倍,这样只要发现环就退出
            //并且ans保存最大的k值
            k1 = next(n, k1); if(k1 > ans) ans = 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值