UVA - 11549:Calculator Conundrum

Calculator Conundrum

来源:UVA

标签:

参考资料:《算法竞赛入门经典——训练指南》

相似题目:

题目

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?”

输入

The first line of the input contains an integer t (1 ≤ t ≤ 200), the number of test cases. Each test case contains two integers n (1 ≤ n ≤ 9) and k (0 ≤ k < 10n) where n is the number of digits this calculator can display k is the starting number.

输出

For each test case, print the maximum number that Alice can get by repeatedly squaring the starting number as described.

输入样例

2
1 6
2 99

输出样例

9
99

参考代码1(530ms)

#include
#include
using namespace std;

int buf[100];
int next(int n,int k){
	if(!k) return 0;
	long long k2=(long long)k*k;
	int L=0;
	while(k2>0){
		buf[L++]=k2%10;
		k2/=10;
	}
	if(n>L) n=L;
	int ans=0;
	for(int i=0;i<n;i++){
		ans=ans*10+buf[--L];
	}
	return ans;
}

int main(){
	int T;
	scanf("%d",&T);
	while(T--){
		int n,k;
		scanf("%d%d",&n,&k);
		set<int> s;
		int ans=k;
		while(!s.count(k)){
			s.insert(k);
			if(k>ans) ans=k;
			k=next(n,k);
		}
		printf("%d\n",ans);
	}
	return 0;
}

参考代码2(150ms)

#include
#include
using namespace std;

int buf[100];
int next(int n,int k){
	if(!k) return 0;
	long long k2=(long long)k*k;
	int L=0;
	while(k2>0){
		buf[L++]=k2%10;
		k2/=10;
	}
	if(n>L) n=L;
	int ans=0;
	for(int i=0;i<n;i++){
		ans=ans*10+buf[--L];
	}
	return ans;
}

int main(){
	int T;
	scanf("%d",&T);
	while(T--){
		int n,k;
		scanf("%d%d",&n,&k);
		int ans=k;
		int k1=k,k2=k;
		do{
			k1=next(n,k1);
			k2=next(n,k2);
			if(k2>ans) ans=k2;
			k2=next(n,k2);
			if(k2>ans) ans=k2;
		}while(k1!=k2);
		printf("%d\n",ans);
	}
	return 0;
}

你可能感兴趣的:(【记录】算法题解)