小白月赛22 A : 操作序列

A:操作序列

析题得说:

考察点 : 模拟,STL库容器的使用
坑点 :   区间不要搞丢东西

难点 :

这个题比较变态的是我们不知道每次输入每行是一个数还是两个数,就需要进行判断,
怎么判断呢?用 scanf 的话遇到空格就 stop 了,那么我们只能选择用字符串进行
处理了,因为两个数之间会有空格进行断开(出题人还是比较良心的)
然后挨个处理就行了。

Code :

#include <map>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int maxn = 1e6 + 10;

map<int,int>maps;
map<int,int>::iterator it;

string str;
int n;

int main(void) {
    scanf("%d",&n);
    string s;
        // 吸收换行字符
    getline(cin, s);
    while(n --) {
        getline(cin,str);
        if(str[0] == '-') {
            if(maps.size()) {
                for(it = maps.begin(); it != maps.end(); it ++) {
                    cout << it -> second << endl;
                                        // 最好删除掉,不能 maps[it ->first] = 0
                                        // 这样的话这个数还是存在的
                    maps.erase(maps.begin());
                    break;
                }
            } else cout << "skipped" << endl;
        } else {
            int i = 0,x = 0,y = 0;
            for(i = 0; i < str.size(); i ++) {
                                // 将前面的一部分转换成 整数
                if(str[i] != ' ') x = x * 10 + str[i] - '0';
                else break;
            }
            if(i == str.size()) {
                                // 说明只有一个数
                if(maps.find(x) != maps.end())
                                // 查找这个数是否存在,不能直接输出 maps[x],容易出错
                cout << maps[x] << endl;
                else 
                cout << 0 << endl;
            } else {
                for(i ++; i < str.size(); i ++) {
                    if(str[i] != ' ')
                        y = y * 10 + str[i] - '0';
                    else
                        break;
                }
                                // 看在这个范围内是否存在其他的女数
                                // 后面 + 31 是因为 有可能正好是 x + 30 这个数
                if(maps.lower_bound(x - 30) == maps.lower_bound(x + 31)) {
                    maps[x] += y;
                }
            }
        }
    }
    return 0;
}

后记 :

1、学到用字符串进行处理不知道会有多少输入的值
2、对 map 有了更深的了解

猜你喜欢

转载自www.cnblogs.com/prjruckyone/p/12354079.html