乐于分享
好东西不私藏

C++算法基础第2章练习-STL标准模板库

C++算法基础第2章练习-STL标准模板库

P5250 【深基17.例5】木材仓库

#include<bits/stdc++.h>using namespace std;set<int> s;intmain(){    int m, op, x;    scanf("%d", &m);    while (m--) {        scanf("%d%d", &op, &x);        if (op == 1) {//进货            if (!s.insert(x).second) {                printf("%s\n""Already Exist");            }        } else {//出货            if (s.empty()) {//仓库是空的                printf("%s\n""Empty");                continue;            }            if (s.find(x) != s.end()) {//存在长度为x的木材                printf("%d\n", x);                s.erase(x);//出库(根据元素内容删除指定元素)            } else {//不存在长度为x的木材                //返回第一个大于等于x的位置,但是到这就只存在大于的情况了                set<int>::iterator index = s.upper_bound(x);                if (index == s.end()) {//说明没找到第一个大于x的位置                    //输出最后一个有效元素                    index--;                    printf("%d\n", *index);                    s.erase(index);//出库(根据元素位置删除指定元素)                    continue;                }                //找到了第一个大于x的位置,位处集合的第一个,说明没有比x短的木材,直接出库                if (index == s.begin()) {                    printf("%d\n", *index);                    s.erase(index);                    continue;                }                //找到了第一个大于x的位置,位处集合的中间,说明有比x短的木材也有比x长的木材                set<int>::iterator before = index;                before--;//比x短的木材                if (x - *before <= *index - x) {//比x短的木材更接近木材的长度                    //出库比较短的木材                    printf("%d\n", *before);                    s.erase(before);                    continue;                } else {                    //出库比较长的木材                    printf("%d\n", *index);                    s.erase(index);                }            }        }    }    return 0;}

P5266 【深基17.例6】学籍管理

#include<bits/stdc++.h>using namespace std;map<string, int> scores;int main() {    int n;    scanf("%d", &n);    string name;    int op, score;    while (n--) {        cin >> op;        if (op == 1) {//插入修改            cin >> name >> score;            scores[name] = score;            printf("%s\n""OK");        } else if (op == 2) {//查询            cin >> name;            if (scores.find(name) != scores.end()) {//存在                printf("%d\n", scores[name]);            } else {//不存在                printf("%s\n""Not found");            }        } else if (op == 3) {//删除            cin >> name;            if (scores.find(name) != scores.end()) {//存在                scores.erase(name);                printf("%s\n""Deleted successfully");            } else {//不存在                printf("%s\n""Not found");            }        } else {//汇总            printf("%d\n", scores.size());        }    }    return 0;}