STL模拟题

A Where is the Marble?

Des
给出一个数组,排序后,进行查找,第一个大于等于该询问元素的位置。
Solution
使用二分函数lower_bound即可,或者自己手写二分,前提是排序。
Code
这里就不给代码了,过于easy。

B The SetStack Computer

Des
你有一个集合栈,支持以下操作:
PUSH:空集'{}'入栈
DUP: 把当前栈顶元素赋值一份入栈
UNION:出栈两个集合,把二者的并集入栈
INTERSECT:出栈两个集合,把二者的交集入栈
ADD:出栈两个集合,把先出栈的集合加到后出栈的集合中,把结果入栈
Solution
我们使用一个vector存放所有的集合,根据id存取,栈中就放集合编号,重复的集合放入栈,都是同一个编号,有效节约空间。

set_union()可以求两个集合的并集
set_intersection()可以求两个集合的交集

函数用法传送门
具体细节看代码
Code

#include <bits/stdc++.h>
using namespace std;
typedef set<int> st ;
map<st, int> mp;//记录集合的标号
vector<st> v;//存放集合
int get_id(const st& x)
{
    if(mp.count(x))
    {
        //cout << "getid work\n";
        return mp[x];
    }
    v.push_back(x);
    return mp[x] = v.size() - 1;
}
signed main()
{
    ios::sync_with_stdio(false), cin.tie(0);
    int T, q;
    cin >> T;
    st null, x;//空集合
    while(T-- && cin >> q)
    {
        stack<int> s;//栈中放集合的id,对应集合
        for(int i = 0; i < q; ++i)
        {
            string op;
            cin >> op;
            if(op[0] == 'P') s.push(get_id(null));
            else if(op[0] == 'D') s.push(s.top());
            else
            {
                const st& x1 = v[s.top()]; s.pop();
                const st& x2 = v[s.top()]; s.pop();
                x.clear();
                if(op[0] == 'U')
                    //set_union求两个集合的并集
                    set_union(x1.begin(), x1.end(), x2.begin(), x2.end(),
                              inserter(x, x.begin()));
                if(op[0] == 'I')
                    //set_intersection求两个集合的交集
                    set_intersection(x1.begin(), x1.end(), x2.begin(), x2.end(),
                                     inserter(x, x.begin()));
                if(op[0] == 'A') x = x2, x.insert(get_id(x1));
                s.push(get_id(x));
            }
            cout << v[s.top()].size() << "\n";
        }
        cout << "***\n";
    }
    return 0;
}

C Ananagrams

Des
问有一些单词,排序后,是否不会变成其他单词,处理时不分大小写。
Solution
mp标记时候,统计转换成小写字母处理,这里有一个很有意思的函数,transform,按照自定义的规则去转化。
传送门
Code

#include <bits/stdc++.h>
using namespace std;
vector<string> a, ok;
map<string, int> mp;
string s;
char to_lower(char c)
{
    return tolower(c);
}
string cal(string x)
{
    transform(x.begin(), x.end(), x.begin(), to_lower);
    sort(x.begin(), x.end());
    return x;
}
signed main()
{
    while(cin >> s && s != "#") a.push_back(s), mp[cal(s)]++;
    for(auto& c : a) if(mp[cal(c)] == 1) ok.push_back(c);
    sort(ok.begin(), ok.end());
    for(auto c : ok) cout << c << "\n";
    return 0;
}
posted @ 2022-08-12 09:19  std&ice  阅读(63)  评论(0编辑  收藏  举报