Maximum GCD UVA - 11827
题目不讲了,就是不会输入。。。
解释一下ungetc在这里是怎么实现这道题目的输入的,去网上搜一下都会告诉你ungetc是将读到的一个字符返回到输入流中,那大家可能会有疑问,代码中每次读一个字符然后ungetc,然后立刻scanf(“%d”,a)这样a不应该每次只读进一位数字啊,为什么可以得到多位的数字呢
画个图就明白了
假设我们想读入123 456连个数字,则输入流应该是这样进入
—————
654 321--> 这样我们先读到字符1,发现时数字,将其退回到输入流再执行scanf不久把123一起读进来了嘛
—————
code:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int gcd(int a,int b){
return b ? gcd(b,a%b) : a;
}
int main(){
int t;
int a[105];
char c;
scanf("%d",&t);
while(getchar() != '\n');
while(t--){
int cnt = 0;
while((c = getchar()) != '\n'){
if(c >= '0' && c <= '9'){
ungetc(c,stdin);
scanf("%d",&a[cnt++]);
}
}
int maxx = 0;
for(int i = 0; i < cnt-1; i++){
for(int j = i+1; j < cnt; j++){
int d = gcd(a[i],a[j]);
if(d > maxx) maxx = d;
}
}
printf("%d\n",maxx);
}
return 0;
}