map与红黑树
map 的用法主要有三个
- 离散化数据
- 判重与去重 (set也行) ,快速查询
- 需要 logn 级别的 insert/delete 性能,同时维护元素有序 !!
C++ STL 中的 map/set 都是基于 RB-Tree 实现的,红黑树与之前学过的 AVL树都是平衡树,但是红黑树不追求完全平衡,插入和删除的旋转次数较AVL 树少,插入和删除的复杂度极优于 AVL 树。
- 增删改查 的复杂度都是 log 级别(方便字符串的处理)
- 并且,底层要求模板类实现了比较方法
运用map的有序化输出前:
#include<bits/stdc++.h>
using namespace std;
int m;
string a[100005];
map<string,int> mp;
int cnt=0;
int main(){
scanf("%d",&m);
while(m--){
int op;string s;scanf("%d",&op);
switch (op){
case 1:{
cin>>s;
if(mp.find(s)!=mp.end()){
cout<<"found"<<endl;
break;
}
mp.insert(pair<string,int>(s,10));
a[cnt++]=s;
cout<<"write"<<endl;
break;
}
case 2:{
cin>>s;
if(mp.find(s)==mp.end()){
cout<<"not found"<<endl;
break;
}
mp.erase(s);
int i;
for(i=0;a[i]!=s;i++);
for(int j=i;j<cnt-1;j++){
a[j]=a[j+1];
}//在数组里删除那个字符串
cnt--;
cout<<"erased"<<endl;
break;
}
case 3:{
sort(a,a+cnt);
for(int i=0;i<cnt;i++) cout<<a[i]<<" ";
cout<<endl;
break;
}
default:{
break;
}
}
}
}
运用map的有序化之后:
#include<bits/stdc++.h>
using namespace std;
int m,cnt=0;
map<string,int> mp;
int main(){
scanf("%d",&m);
while(m--){
int op;string s;scanf("%d",&op);
switch (op){
case 1:{
cin>>s;
if(mp.find(s)!=mp.end()){
cout<<"found"<<endl;
break;
}
mp.insert(pair<string,int>(s,10));
cout<<"write"<<endl;
break;
}
case 2:{
cin>>s;
if(mp.find(s)==mp.end()){
cout<<"not found"<<endl;
break;
}
mp.erase(s);
cout<<"erased"<<endl;
break;
}
case 3:{
for(map<string,int>::iterator it=mp.begin();it!=mp.end();it++){//原来map里是按字典排序的
cout<<it->first<<" ";
}
cout<<endl;
break;
}
default:{
break;
}
}
}
}
顺便,如果需要按字典从大到小的话:
for(map<string,int>::iterator it=mp.rbegin();it!=mp.rend();it++){
cout<<it->first<<" ";
}