UVA 11827 Maximum GCD【GCD,stringstream】

来源:互联网 发布:淘宝网黄金 编辑:程序博客网 时间:2024/05/12 17:59

这题没什么好说的,但是输入较特别,为此还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();
0 0
原创粉丝点击