题目链接:点击打开链接
题意:
输入n k,表示计算器能显示n位数字,初始有一个数字k
每次操作 k = k^2, 若超出n位则截取前n位。
求能获得的最大数字。
思路:
首先我们能判断这个操作一定存在循环。
那么如何终止循环,利用Floyd判圈法
让两个循环child1和child2刚开始都为k,然后child1每次变换一次,child2每次变换2次;
这样当child1再次等于child2时说明已经至少经过一个循环节了,因为child2已经从后面赶上child1了
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Scanner; import java.util.TreeSet; import java.util.Queue; public class Main { static int N = 100100; long n, k, maxnum; long work(long x){ x = x*x; while(x>=maxnum)x /= 10; return x; } void work() { int T = cin.nextInt(); while(T-- > 0){ n = cin.nextLong(); k = cin.nextLong(); maxnum = 1; for(int i = 0; i < n; i++)maxnum *= 10; long ans = k; long a = k, b = k; do{ a = work(a); b = work(b); ans = max(ans, b); b = work(b); ans = max(ans, b); }while(a!=b); out.println(ans); } } Main() { cin = new Scanner(System.in); out = new PrintWriter(System.out); } public static void main(String[] args) { Main e = new Main(); e.work(); out.close(); } public Scanner cin; public static PrintWriter out; int upper_bound(int[] A, int l, int r, int val){//upper_bound(A+l,A+r,val)-A; int pos = r; r -- ; while(l <= r){ int mid = (l+r)>>1; if(A[mid]<=val){ l = mid+1; } else { pos = mid; r = mid-1; } } return pos; } /*class Queue { int[] queue = new int[N+10]; int front, rear; // front <= rear Queue() { // queue = new int[x]; } void clear() { front = rear = 1; } boolean empty() { return front == rear; } int size() { return rear - front; } int front() { return queue[front]; } int rear() { return queue[rear - 1]; } void push_rear(int x) { queue[rear++] = x; } void pop_front() { front++; } void pop_rear() { rear--; } } /**/ int max(int x, int y) { return x > y ? x : y; } int min(int x, int y) { return x < y ? x : y; } double max(double x, double y) { return x > y ? x : y; } double min(double x, double y) { return x < y ? x : y; } long max(long x, long y) { return x > y ? x : y; } long min(long x, long y) { return x < y ? x : y; } static double eps = 1e-8; int abs(int x) { return x > 0 ? x : -x; } double abs(double x) { return x > 0 ? x : -x; } boolean zero(double x) { return abs(x) < eps; } }
时间: 2024-10-09 20:36:03