uva11549 老式计算器 (Floyd判圈 )

来源:互联网 发布:淘宝刷单 青青岛 编辑:程序博客网 时间:2024/06/02 20:42
用神奇的Floyd判圈算法。

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

/* ***********************************************Author        :fistyCreated Time  :2014/12/21 22:38:24File 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 1000000000int 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;}


0 0