4479. Gap

来源:互联网 发布:淘宝psp3000 编辑:程序博客网 时间:2024/05/18 02:28

新手赛的题,据说是以前4+2的。老了,都没资格参加。哭

在大牛的指点下,用STL的set解决,嚓,这样编程实现的话简单得多啊惊讶

还好以前有看那本C++ primer,不熟的话,用stl也不是那么好写滴!


主要注意:

  1. set不支持随机访问。所以就只能用自增,自减来移动指针了。
  2. find查找不到返回的是“超出末端的迭代器”。
  3. 注意数据的一种“情况"要考虑周全。
  4. 数据类型用int就够了。

先自己写写看吧。


#include<cstdio>#include<set>using namespace std;int n;int  ans, x;char str[10];int main(){    while ( scanf("%d", &n) != EOF ){        set<int> s;        for (int i=0; i<2; ++i){            scanf("%s %d", str, &x);            s.insert(x);        }        set<int>::iterator curit, preit, posit;        int  curval, posval, preval;                curit = s.begin();        posit = curit;        ++posit;                ans= *posit - *curit;        for (int i=2; i<n; ++i){            scanf("%s", str);            if (str[0]=='A'){                scanf("%d", &x);                if ( s.find(x) == s.end() ){                    s.insert(x);                }else{                    ans = 0;                    continue;                }                curit = s.find(x);                posit = preit = curit;                ++posit;                --preit;                posval = *(posit);                preval = *(preit);                if ( curit != s.begin() && x-preval < ans ){                    ans =  x-preval;                }                if ( posit != s.end()  &&  posval-x < ans ){                    ans = posval - x;                }            }else if ( str[0]=='Q' ){                printf("%d\n", ans);            }        }    }    return 0;}



原创粉丝点击