一、题目描述
二、算法分析说明与代码编写指导
GCD 的时间复杂度是 O(log n),最多 99 组数据,每组最多 99 个整数,也就是说进行 GCD 的次数不超过 1 百万,勉强能卡在时间线上(如果给的整数都比较大)。
题目给的 M 实际上并没有指定,所以必须检测是否读到回车,读到了才能开始算。
本来直接在快读的模板上改,读入数字直到读到空白字符就用 ungetc 把最后读到的空白字符推回到输入流 stdin,如果这个空白字符是回车就开始暴力求解。结果 WA 了。
网上翻题解才知道读入的格式不是严格正确的,所以必须处理好数字之间的空白。
这里给一组测试数据:
3
10 20 30 40
7 5 12
125 15 25
为了锻炼大家阅读代码的能力,本次不作详细注释。
三、AC 代码(0 ms)
#include<cstdio>
#include<cctype>
#include<algorithm>
#pragma warning(disable:4996)
template<class _Ty> _Ty gcd(const _Ty& a, const _Ty& b) {//a, b > 0
return b == 0 ? a : gcd(b, a % b);
}
template<class _Ty> inline void readu(_Ty& x) {
static _Ty c; x = 0;
for (;;) {
c = getchar();
if (!isdigit(c)) { ungetc(c, stdin); return; }
x = (x << 3) + (x << 1) + c - '0';
}
}
inline bool hasnewline() {
static int c; bool has = false;
for (;;) {
c = getchar(); if (c == '\n')has = true;
if (c > 32 || c == EOF) { ungetc(c, stdin); return has; }
}
}
unsigned n, m, a[100], g; int c;
int main() {
while ((c = getchar()) <= ' ') {}
ungetc(c, stdin);
readu(n); ++n;
while ((c = getchar()) <= ' ') {}
ungetc(c, stdin);
while (--n) {
m = 0; g = 0;
for (;;) { readu(a[m]); ++m; if (hasnewline() == true)break; }
for (unsigned i = 0; i < m; ++i)
for (unsigned j = i + 1; j < m; ++j)
g = std::max(g, gcd(a[i], a[j]));
printf("%u\n", g);
}
return 0;
}