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(530 ms)
#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
"
,ans); } return 0; }

リファレンスコード2(150 ms)
#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
"
,ans); } return 0; }