UVA 11827 Maximum GCD(读入技巧,stringstream的使用)

好久没来写blog了,不能颓了。

这道题的数据范围很小,n<=100.所以直接暴力就可以解决问题,然后,我们发现这个题的读入长度并没有要求,那么我们就需要应用stringstream这个字符串输入流

 题目:

Given the N integers, you have to nd the maximum GCD (greatest common divisor) of every possible
pair of these integers.
Input
The rst line of input is an integer N (1 < N < 100) that determines the number of test cases.
The following N lines are the N test cases. Each test case contains M (1 < M < 100) positive
integers that you have to nd the maximum of GCD.
Output
For each test case show the maximum GCD of every possible pair.
Sample Input
3
10 20 30 40
7 5 12
125 15 25
Sample Output
20
1
25

 

代码:

#include<cstdio>
#include<iostream>
#include<sstream>
#include<string>
using namespace std;

int num[100], n;
string s;

int gcd(int a, int b)
{
    return b ? gcd(b, a % b) : a;
}

int cal()
{
    int i, j, maxn = 0;
    for (i = 0; i < n - 1; ++i)
        for (j = i + 1; j < n; ++j)
            maxn = max(maxn, gcd(num[i], num[j]));
    return maxn;
}

int main()
{
    int t;
    scanf("%d\n", &t);
    while (t--)
    {
        getline(cin, s);//读入的是string类型的数据
        stringstream ss(s);//定义了一个输入流
        n = 0;
        while (ss >> num[n])//将字符串转化为int类型的数据,遇到空格和回车就结束转换
            ++n;
        printf("%d\n", cal());
    }
    return 0;
}

 

posted @ 2015-08-17 12:16  BYYB_0506  阅读(273)  评论(0编辑  收藏  举报