UVA 11549 - Calculator Conundrum(模拟+周期规律)

Problem C

CALCULATOR CONUNDRUM

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

Program Input

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

Program Output

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

Sample Input & Output

INPUT

2
1 6
2 99
OUTPUT
9
99
题意:一个能显示n位的计算器,一开始输入k,然后不断平方,如果超过位数,就只保留前n位,平方过程中最大得到的数字是多少。
思路:数字不断乘,到最后会成周期规律,然后就不断去找最大数,用set记录重复的数字(因为数字挺大数组开不下)。
上面是我的思路,这个思路写起来时间效率并不高,因为set这个东西不是非常快,还有一个方法叫floyd判圈法,就是一个数字每次平方一次,一个每次平方两次,如果数字相等,就说明形成周期了,这就相当于赛跑套圈一个道理。一个速度比较快,一个比较慢,早晚会有追上的时候(即相等的时候)。
代码:
set版:
#include 
#include 
#include 
#define max(a,b) ((a)>(b)?(a):(b))
using namespace std;

int t, n;
long long k;
set vis;

void init() {
	vis.clear();
	scanf("%d%lld", &n, &k);
}

long long Pow(long long k) {
	long long ans = 0;
	long long t = k * k;
	long long save[20];
	int saven = 0;
	while (t) {
		save[saven++] = t % 10;
		t /= 10;
	}
	for (int i = saven - 1; i > max(saven - 1 - n, -1); i--)
		ans = ans * 10 + save[i];
	return ans;
}

int solve() {
	int ans = 0;
	while (vis.find(k) == vis.end()) {
		if (ans < k) ans = k;
		vis.insert(k);
		k = Pow(k);
	}
	return ans;
}

int main() {
	scanf("%d", &t);
	while (t--) {
		init();
		printf("%d\n", solve());
	}
	return 0;
}

floyd判圈法:
#include 
#include 
#define max(a,b) ((a)>(b)?(a):(b))

int t, n;
long long k;

void init() {
	scanf("%d%lld", &n, &k);
}

long long Pow(long long k) {
	long long ans = 0;
	long long t = k * k;
	long long save[20];
	int saven = 0;
	while (t) {
		save[saven++] = t % 10;
		t /= 10;
	}
	for (int i = saven - 1; i > max(saven - 1 - n, -1); i--)
		ans = ans * 10 + save[i];
	return ans;
}

int solve() {
	long long k1 = k, k2 = k, ans = k;
	while (1) {
		k1 = Pow(k1);
		k2 = Pow(k2); ans = max(ans, k2);
		k2 = Pow(k2); ans = max(ans, k2);
		if (k1 == k2) break;
	}
	return ans;
}

int main() {
	scanf("%d", &t);
	while (t--) {
		init();
		printf("%lld\n", solve());
	}
	return 0;
}


你可能感兴趣的:(算法设计-推理)