UVA 11827 Maximum GCD【GCD,stringstream】

这题没什么好说的,但是输入较特别,为此还WA了一次。。。

题目链接:

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2927

题意:

输入m个数,求两两一组的最大GCD。

分析:

对stringstream不太熟悉,直接模拟字符串的输入,但是wa了。
我觉得wa的原因是,如果一行末尾有空格的话,就不能正确输入了。。。还求指正。。。

  int a;
  char c;
  bool flag = true;
  int cnt = 0;
  while(flag|| c == ' '){
     sa(a);
     t[cnt++] = a;
     flag = false;
     scanf("%c", &c);
  }

代码:

使用stringstream的正确方式。

#include<cstdio>
#include<iostream>
#include <sstream>
#include<cstring>
using namespace std;
#define sa(a) scanf("%d", &a)
const int maxn = 100 + 5;
int t[maxn];
int gcd(int a, int b)
{
    return b? gcd(b, a % b) : a;
}
int main (void)
{
    int n;sa(n);
    getchar();
    string s;
    stringstream ss(s);
    while(n--){
        int cnt = 0;
        ss.str("");
        ss.clear();
        getline(cin, s);
        ss<<s;
        while(ss>>t[cnt]) {
          cnt++;
        }
        int ans = 0;
        for(int i = 0; i < cnt; i++){
            for(int j = i + 1; j < cnt; j++){
                ans = max(ans, gcd(t[i], t[j]));
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}

注意:

  1. str() 是返回内部缓冲区的一个copy, str(“”) 是清空内部缓冲区。

有关清空stringstream

  1. 只使用ss.str(“”),可以把前面的字串清空,但是此时ss的串流已经到尾端了(eof),判定为error flag,所以根本无法写入。
  2. 只使用ss.clear(),只是清空了flag,但是前面的字符串没有清空,直接打印ss.str()的话会把之前的串也打出来。
  3. 所以清空必须是 ss.str(""); ss.clear();

转载于:https://www.cnblogs.com/Tuesdayzz/p/5758674.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值