USACO Palindromic Squares

Code

Notice the upper bound of maxn.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
ID: wcr19961
PROG: palsquare
LANG: C++11
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;

typedef long long LL;
const int maxn = 30;
int k[maxn], kk[maxn];

int main() {
freopen("palsquare.in", "r", stdin);
freopen("palsquare.out", "w", stdout);
int n;
scanf("%d", &n);
for (int i = 1; i <= 300; ++i) {
int sum = i * i, len = 0;
while (sum) {
k[len++] = sum % n;
sum /= n;
}
bool ok = true;
for (int j = 0; j < len; ++j) {
if (k[j] != k[len - 1 - j]) {
ok = false;
break;
}
}
if (ok) {
int tmp = i, tmplen = 0;
while (tmp) {
kk[tmplen++] = tmp % n;
tmp /= n;
}
for (int j = tmplen - 1; j >= 0; --j) {
putchar(kk[j] < 10 ? kk[j] + '0' : kk[j] + 'A' - 10);
}
putchar(' ');
for (int j = 0; j < len; ++j) {
putchar(k[j] < 10 ? k[j] + '0' : k[j] + 'A' - 10);
}
puts("");
}
}
return 0;
}