Maximum GCD : http://acm.hust.edu.cn/vjudge/contest/view.action?cid=109329#problem/F
有关最大公约数的问题已经处理了一万道了,虽然这个题的数据比较小,但是由于题目要求的输入比较不一般,还是想了好久才敢继续做下去。
本题的关键就是在于一个把一个或多个字符退回的输入流函数有关——ungetc(),还有其中对'\n'的处理,当把一个字符串转化成整型数组之后,再用暴力枚举的方法去求解最大公约数即可,正常求,没问题。
代码实现如下:
#include <iostream>
#include <cstdio>
using namespace std;
int gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
int main()
{
int n;
int data[110];
int max,count;
char c;
scanf("%d",&n);
while(getchar()!='\n'); //防止输入一个n之后多输入几个回车
while(n--)
{
count=0;
max=-999;
while((c=getchar())!='\n')
{
if(c>='0'&&c<='9')
{
ungetc(c,stdin);
scanf("%d",&data[count++]);
}
}
for(int i=0;i<count;i++)
{
for(int j=i+1;j<count;j++)
{
int t=gcd(data[i],data[j]);
if(t>max)
{
max=t;
}
}
}
printf("%d\n",max);
}
return 0;
}
int ungetc(char ch,FILE*stdin) c为要退回的字符,stdin为要退回的输入流;若函数执行成功,则返回非零值,否则,返回零。