Calculator Conundrum UVA - 11549 计算器谜题 Floyd判圈算法

版权声明:本文为博主原创文章,未经博主允许不得转载,欢迎添加友链。 https://blog.csdn.net/qq_42835910/article/details/89816615

     Alice got a hold of an old calculator that can display n digits. She was bored enough to come up with the following time waster.

     She enters a number k then repeatedly squares it until the result overflows. When the result overflows, only the n most significant digits are displayed on the screen and an error flag appears. Alice can clear the error and continue squaring the displayed number. She got bored by this soon enough, but wondered:

         “Given n and k, what is the largest number I can get by wasting time in this manner?” 

分析:逐个模拟,直到得到的数重复出现。

方法一:Floyd判圈法。在一个线性的跑道上,A,B同时出发,B的速度是A的两倍,如果跑道没有环,那么B将永远领先A,如果有环,那么经过一段时间之后B一定能追上A。

#include <cstdio>
int nums[101];
int calculate(int n,int k){
	long long res =  (long long)k * k;
	int cnt = 0, ans = 0;
	while(res ){
		nums[cnt++] = res % 10;
		res /= 10;
	}
	for(int i = 0; i < n; i++) // 倒过来取 
		ans = ans *10 + nums[--cnt]; 
	return ans;
}

int main(int argc, char** argv) {
	int t;
	scanf("%d",&t);
	while(t--){
		int n, k;
		scanf("%d%d",&n,&k);
		int ans = k, k1 = k, k2 = k;
		do{
			k1 = calculate(n,k1);
			k2 = calculate(n,k2); if(k2 > ans) ans = k2;
			k2 = calculate(n,k2); if(k2 > ans) ans = k2;
		} while(k1 != k2);
		printf("%d\n",ans);
	} 
	return 0;
}

方法二:set判重。

#include <cstdio>
#include <set>
using namespace std;

set <int> vis;
int nums[101];
int Calculate(int n,int k){
	long long res =  (long long)k * k;
	int cnt = 0, ans = 0;
	while(res ){
		nums[cnt++] = res % 10;
		res /= 10;
	}
	for(int i = 0; i < n; i++) // 倒过来取 
		ans = ans *10 + nums[--cnt]; 
	return ans;
}

int main(int argc, char** argv) {
	int t;
	scanf("%d",&t);
	while(t--){
		int n, k;
		vis.clear();
		scanf("%d%d",&n,&k);
		int ans = k;
		while(!vis.count(k)){
			vis.insert(k);
			k = Calculate(n,k);			
			if(k > ans) ans = k;			
		}
		printf("%d\n",ans);
	} 
	return 0;
}

方法三:set判重,stringstream处理 。

#include <cstdio>
#include <iostream>
#include <set>
#include <sstream>
using namespace std;

set <int> vis;
int Calculator(int n,int k){
	stringstream ss;
	ss << (long long)k * k;
	string s = ss.str();
	if(s.length() > n) s = s.substr(0,n);
	stringstream ss2(s);
	ss2 >> k;
	return k;
}

int main(int argc, char** argv) {
	int t;
	scanf("%d",&t);
	while(t--){
		int n, k;
		vis.clear();
		scanf("%d%d",&n,&k);
		int ans = k;
		while(!vis.count(k)){
			vis.insert(k);
			k = Calculator(n,k);			
			if(k > ans) ans = k;			
		}
		printf("%d\n",ans);
	} 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42835910/article/details/89816615