目录
引言
STL(Standard Template Library)是C++的标准模块库。对于算法竞赛,它提供大量实用的工具。本篇将介绍STL中的一些常用算法和容器。
STL初步
1-1 排序与检索
sort()
sort()可以对任意对象排序。排序对象可存于普通数组,也可存于C++容器,前者用sort(a,a+n)调用,后者用sort(a.begin(),a.end())调用。
#include<bits/stdc++.h>
using namespace std;
#define rep(i,j,k) for(int i=j;i<=k;i++)
int main(){
string a{"fjsdkahf"};
int b[]{3,5,2,1,7,5,4};
sort(a.begin(), a.end());
sort(b, b+7);//这里是7不是6
cout << a << endl;
rep(i,0,6) cout << b[i] << " ";
return 0;
}
sort()默认从小到大排序(升序)。想要改变其功能,可以通过第三个参数自定义排序。
#include<bits/stdc++.h>
using namespace std;
#define rep(i,j,k) for(int i=j;i<=k;i++)
template<typename T>
bool cmp(T a, T b){
return a>b;
}
int main(){
string a{"fjsdkahf"};
int b[]{3,5,2,1,7,5,4};
sort(a.begin(), a.end(), cmp<char>);
sort(b, b+7, cmp<int>);
cout << a << endl;
rep(i,0,6) cout << b[i] << " ";
return 0;
}
也可以使用lambda表达式:Lambda是C++中一个非常强大的特性,使得编写内联函数更加简单和直观,特别是在需要临时函数对象的场景中非常有用。
#include<bits/stdc++.h>
using namespace std;
#define rep(i,j,k) for(int i=j;i<=k;i++)
int main(){
string a{"fjDsdkSf"};
int b[]{3,5,2,1,7,5,4};
sort(a.begin(), a.end(), [](char a, char b){
if (islower(a) != islower(b)) {//把大写字母排在末尾
return bool(islower(a));
}
return a<b;
});
sort(b, b+7, [](int a, int b){
return a>b;
});
cout << a << endl;
rep(i,0,6) cout << b[i] << " ";
return 0;
}
lower_bound()
让我们回到最开始的升序序列。已知其中一个元素,如何知道它的位置?对于已经升序排序的数列,可以调用lower_bound()找出该元素第一次出现的位置。
#include<bits/stdc++.h>
using namespace std;
int main(){
int b[]{1,2,3,5,6,6,7};
int p=lower_bound(b,b+7,5) - b;//地址相减得到b[p]==5
cout << p+1;//5在数列中排第p+1位
return 0;
}
请读者自行实验一个序列中不存在的元素,看看结果如何。
练习
UVa 10474 Online Judge
1-2 不定长数组:vector
vector
普通数组一经声明即确定其大小。而vector不受这个限制。
创建vector:
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<int> a(5,0);//长度为5,初始化为零
for(int i=0;i<5;i++){
cout << a[i] << " ";//0 0 0 0 0
}
}
当然,作为不定长数组,完全可以声明空数组,用push_back()函数在数组末尾添加元素,pop_back()可以删除最后一个元素。
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<int> a;
for(int i=0;i<5;i++){
a.push_back(i*i);
}
for(int b:a){
cout << b << " ";//0 1 4 9 16
}
cout << endl;
a.pop_back();
for(int i=0;i<a.size();i++){
cout << a[i] << " ";//0 1 4 9
}
}
resize(n,m)可以改变其大小为n,初始化为m。clear()可以清空,empty()可以测试是否为空。
#include<bits/stdc++.h>
using namespace std;
int main() {
vector<int> myVector = {1, 2, 3, 4, 5};
myVector.resize(7, 0);
for(int i : myVector) cout << i << " ";//1 2 3 4 5 0 0
cout << endl;
myVector.resize(3);
for(int i : myVector) cout << i << " ";//1 2 3
cout << endl;
myVector.clear();
if(myVector.empty()) cout << "myVector is empty." << endl;
return 0;
}
练习
UVa 101 Online Judge
1-3 集合:set
set
set是数学上的集合:每个元素最多出现一次。和sort一样,set默认从小到大排序。可以自定义set,但同样必须定义“小于”运算符。
创建set及基本操作:
#include <bits/stdc++.h>
using namespace std;
int main() {
// 创建set
set<int> mySet;
// 向set中插入元素
mySet.insert(1);
mySet.insert(2);
mySet.insert(3);
mySet.insert(2); // 这个插入操作将被忽略,因为2已经存在
// 显示set内容
cout << "Set after insertion: ";
for (const auto& element : mySet) {
cout << element << " ";//1 2 3
}
cout << endl;
// 从set中删除元素
mySet.erase(2);
// 显示删除元素后的set
cout << "Set after deletion: ";
for (const auto& element : mySet) {
cout << element << " ";//1 3
}
cout << endl;
// 查找元素
auto it = mySet.find(2);
if (it != mySet.end()) {//mySet.end()指向最后一个元素的下一位
cout << "Element '2' found in set." << endl;
} else {
cout << "Element '2' not found in set." << endl;
}
// 另一种遍历set
cout << "Iterating over set: ";
for (auto it = mySet.begin(); it != mySet.end(); ++it) {//it类型为set<int>::iterator
cout << *it << " ";//1 3
}
cout << endl;
return 0;
}
自定义set:
#include <bits/stdc++.h>
using namespace std;
struct Person {
string name;
int age;
// 构造函数
Person(string n, int a) : name(n), age(a) {}
// 比较运算符,首先按name排序,如果name相同,则按age排序
bool operator < (const Person& p) const {
if (name == p.name) {
return age < p.age;
}
return name < p.name;
}
};
int main() {
// 创建一个Person类型的set
set<Person> mySet;
// 向set中插入Person对象
mySet.insert(Person("Alice", 30));
mySet.insert(Person("Bob", 25));
mySet.insert(Person("Alice", 25)); // 即使名字相同,年龄不同也会被插入
mySet.insert(Person("Charlie", 35));
// 遍历set并打印元素
for (const auto& person : mySet) {
cout << person.name << ", " << person.age << endl;
}
return 0;
}
练习
UVa 10815 Online Judge
1-4 映射:map
map
map是从键(key)到值(value)的映射。
#include<bits/stdc++.h>
using namespace std;
int main(){
map<string, int> month_to_number = {{"January", 1}, {"February", 2}};//创建map并初始化
month_to_number["July"] = 7;
month_to_number.insert(make_pair("March", 3));
month_to_number.insert({"April", 4});
month_to_number.emplace("May", 5);
for (auto it = month_to_number.begin(); it != month_to_number.end(); it++)
cout << it->first << " " << it->second << endl;
return 0;
}
练习
UVa 156 Online Judge
1-5 栈 stack
stack
stack实现栈 ,即“先进后出”的数据结构。push()和pop()实现元素入栈和出栈,top()取栈顶元素。
#include<bits/stdc++.h>
using namespace std;
int main() {
// 创建一个空的栈
stack<int> stack;
// 向栈中添加元素
stack.push(10);
stack.push(20);
stack.push(30);
// 显示栈顶元素
cout << "栈顶元素为: " << stack.top() << endl;
// 移除栈顶元素
stack.pop();
// 再次显示栈顶元素
cout << "新的栈顶元素为: " << stack.top() << endl;
// 检查栈是否为空
if (!stack.empty()) {
cout << "栈不为空" << endl;
}
// 显示栈中的元素数量
cout << "栈中的元素数量为: " << stack.size() << endl;
return 0;
}
补充:inserter()
#include<bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
vector<int> new_elements = {10, 20, 30};
// 使用inserter插入元素到v
copy(new_elements.begin(), new_elements.end(), inserter(v, v.begin() + 2));
// 输出更新后的v
cout << "v的元素: ";
for (int elem : v) {
cout << elem << " ";//1 2 10 20 30 3 4 5
}
cout << endl;
return 0;
}
补充:set_union()
#include<bits/stdc++.h>
using namespace std;
int main() {
// 创建并初始化两个已排序的vector
vector<int> v1 = {1, 2, 4, 5, 6};
vector<int> v2 = {2, 5, 7, 8};
// 创建一个vector来存放结果
vector<int> result(v1.size() + v2.size());
// 计算并集
auto it = set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), result.begin());
// 调整大小以去除未初始化的部分
result.resize(it - result.begin());
// 输出结果
cout << "并集结果:";
for (int x : result) {
std::cout << x << ' ';//1 2 4 5 6 7 8
}
cout << std::endl;
return 0;
}
补充:set_intersection()
#include<bits/stdc++.h>
using namespace std;
int main() {
// 创建并初始化两个已排序的vector
vector<int> v1 = {1, 2, 4, 5, 6};
vector<int> v2 = {2, 5, 7, 8};
// 创建一个vector来存放结果
vector<int> result(min(v1.size(), v2.size())); // 交集的大小不会超过较小集合的大小
// 计算交集
auto it = set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), result.begin());
// 调整大小以去除未初始化的部分
result.resize(it - result.begin());
// 输出结果
cout << "交集结果:";
for (int x : result) {
cout << x << ' ';// 2 5
}
cout << endl;
return 0;
}
练习
UVa 12096 Online Judge
1-6 队列 queue
队列是符合“先进先出”的数据结构,可以用queue<int> s方式声明:
#include<bits/stdc++.h>
using namespace std;
int main() {
// 创建一个int类型的队列
queue<int> q;
// 入队操作
q.push(10);
q.push(20);
q.push(30);
// 显示队首和队尾元素
cout << "Front element: " << q.front() << endl;
cout << "Back element: " << q.back() << endl;
// 出队操作
q.pop();
cout << "Front element after one pop: " << q.front() << endl;
// 检查队列是否为空
if (!q.empty()) {
cout << "Queue is not empty." << endl;
}
// 显示队列中的元素数量
cout << "Queue size: " << q.size() << endl;
return 0;
}
练习
Uva 540 Online Judge
优先队列 priority_queue
优先队列类似于队列,但先出列的元素是队列中优先级最高的元素。由于出队元素不是最先进队的元素,出队方法从queue的front()变为top()。
#include<bits/stdc++.h>
using namespace std;
int main() {
priority_queue<int> pq;
// 向 pq 中添加元素
pq.push(30);
pq.push(100);
pq.push(25);
pq.push(40);
// 显示 pq 中的最大元素
cout << "The largest element is " << pq.top() << '\n';
// 删除最大元素
pq.pop();
// 再次显示最大元素
cout << "Now the largest element is " << pq.top() << '\n';
return 0;
}
priority_queue<int, vector<int>, greater<int> > pq可以让越小的整数优先级越大。
#include<bits/stdc++.h>
using namespace std;
int main() {
// 创建一个最小堆优先队列
priority_queue<int, vector<int>, greater<int> > min_heap;
// 向优先队列中添加元素
min_heap.push(10);
min_heap.push(30);
min_heap.push(20);
min_heap.push(5);
min_heap.push(1);
cout << "Elements in the priority queue (min-heap):" << endl;
// 访问和删除元素,直到队列为空
while (!min_heap.empty()) {
// 打印当前的最小元素
cout << min_heap.top() << " ";//1 5 10 20 30
// 移除当前的最小元素
min_heap.pop();
}
cout << endl;
return 0;
}
练习
UVa 136 Online Judge
练习参考答案
2-1
#include<bits/stdc++.h>
using namespace std;
#define rep(i,j,k) for(int i=j;i<=k;i++)
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);//关闭同步省时间
int m, n, x, a[10001], count=0;
while(cin >> m >> n && m){
cout << "CASE# " << ++count << ":\n";
rep(i,0,m-1) cin >> a[i];
sort(a, a+m);
rep(i,0,n-1){
cin >> x;
int p=lower_bound(a,a+m,x)-a;
if(a[p]==x) cout << x << " found at " << p+1 << "\n";//"\n"比endl快
else cout << x << " not found" << "\n";
}
}
return 0;
}
2-2
#include<bits/stdc++.h>
using namespace std;
#define rep(i,j,k) for(int i=j;i<k;i++)
int n;
vector<int> pile[25];//每个pile[i]是一个vector
//找木块a的位置,&返回值
void find_block(int a, int& p, int& h) {
for(p = 0; p < n; p++) {//这里不能使用rep宏,宏无法保持引用传递的语义
for(h = 0; h < pile[p].size(); h++) {
if(pile[p][h] == a) return;
}
}
}
//第p堆h以上木块归位
void clear_above(int p, int h){
rep(i,h+1,pile[p].size()){
int x = pile[p][i];
pile[x].push_back(x);//放回原位
}
pile[p].resize(h+1);//只保留0~h
}
//第p堆h及以上木块整体移动到p2顶部
void pile_onto(int p, int h, int p2){
rep(i,h,pile[p].size())
pile[p2].push_back(pile[p][i]);
pile[p].resize(h);
}
void print(){
rep(i,0,n){
cout << i << ":";
rep(j,0,pile[i].size()) cout << " " << pile[i][j];
cout << "\n";
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int a, b;
string s1, s2;
cin >> n;
rep(i, 0, n) pile[i].push_back(i);
while(cin >> s1 >> a >> s2 >>b){
int pa, pb, ha, hb;
find_block(a, pa, ha);
find_block(b, pb, hb);
if(pa == pb) continue;//非法指令
if(s2 == "onto") clear_above(pb, hb);
if(s1 == "move") clear_above(pa, ha);
pile_onto(pa, ha, pb);
}
print();
return 0;
}
2-3
#include<bits/stdc++.h>
using namespace std;
set<string> dic;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
string s, voc;
while(cin >> s){
for(int i=0;i<s.length();i++)
if(isalpha(s[i])) s[i]=tolower(s[i]);else s[i]=' ';
stringstream ss(s);
while(ss >> voc) dic.insert(voc);
}
for(auto it=dic.begin();it!=dic.end();it++)//it类型为set<string>::iterator
cout << *it << "\n";
return 0;
}
2-4
#include<bits/stdc++.h>
using namespace std;
map<string,int> cnt;
vector<string> word;
string stdlize(const string& s){
string ans;
for(const char& c: s) ans+=tolower(c);
sort(ans.begin(), ans.end());
return ans;
}
int main(){
string s;
while(cin >> s){
if(s[0]=='#') break;
word.push_back(s);
string l = stdlize(s);
if(!cnt.count(l)) cnt[l] = 0;
cnt[l]++;
}
vector<string> ans;
for(const auto& e : word)
if(cnt[stdlize(e)] == 1) ans.push_back(e);
sort(ans.begin(), ans.end());
for(const auto& e : ans)
cout << e << "\n";
return 0;
}
2-5
#include<bits/stdc++.h>
using namespace std;
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
typedef set<int> Set;
map<Set,int> IDcache;//把集合映射为ID
vector<Set> Setcache;//根据ID取集合
int ID (Set x) {
if (IDcache.count(x)) return IDcache[x];
Setcache.push_back(x);//添加新集合
return IDcache[x] = Setcache.size() - 1;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int T;
cin >> T;
while(T--){
stack<int> s;
int n;
cin >> n;
for(int i = 0; i < n ; i++) {
string op;
cin >> op;
if (op[0] == 'P') s.push(ID(Set()));
else if (op[0] == 'D') s.push(s.top());
else {
Set x1 = Setcache[s.top()]; s.pop();
Set x2 = Setcache[s.top()]; s.pop();
Set x;
if (op[0] == 'U') set_union(ALL(x1), ALL(x2), INS(x));
if (op[0] == 'I') set_intersection(ALL(x1), ALL(x2), INS(x));
if (op[0] == 'A') { x = x2; x.insert(ID(x1)); }
s.push(ID(x));
}
cout << Setcache[s.top()].size() << "\n";
}
cout << "***\n";
}
return 0;
}
2-6-1
#include<bits/stdc++.h>
using namespace std;
const int maxt = 1010;
int main() {
int t, kase = 0;
while(cin >> t && t){
cout << "Scenario #" << ++kase << "\n";
//记录所有人团体编号
map<int, int> team;//team[x]表示编号为x的人所在团队编号
for(int i=0;i<t;i++){
int n, x;
cin >> n;
while(n--){
cin >> x;
team[x] = i;
}
}
//模拟
queue<int> q, q0[maxt];//q为团体队列,q0[i]为团队i成员的队列
for(;;) {
int x;
string cmd;
cin >> cmd;
if(cmd[0] == 'S') break;
else if(cmd[0] == 'D') {
int t = q.front();
cout << q0[t].front() << "\n";
q0[t].pop();
if(q0[t].empty()) q.pop();//团体t全体出队列
}
else if(cmd[0] == 'E') {
cin >> x;
int t = team[x];
if(q0[t].empty()) q.push(t);
q0[t].push(x);
}
}
cout << "\n";
}
return 0;
}
2-6-2
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int coe[3] {2, 3, 5};
int main() {
priority_queue<LL, vector<LL>, greater<LL> > pq;
set<LL> s;
pq.push(1);
s.insert(1);
for(int i=1;;i++){
LL x = pq.top(); pq.pop();
if(i == 1500) {
cout << "The 1500'th ugly number is " << x << ".\n";
break;
}
for(int j = 0; j < 3; j++) {
LL x2 = x * coe[j];
if(!s.count(x2)) { s.insert(x2); pq.push(x2); }
}
}
return 0;
}