about map
About map
简介
在 STL 中的 map,是由红黑树实现的,理论复杂度都是 \(O(\log n)\),但实际中,由于使用错误,复杂度往往超过 \(O(\log n)\) 的,于是常常被人——。所以现在我来给你们扫雷。
例题
错误写法
#include<bits/stdc++.h>
#define int long long
using namespace std;
map<int,int> t;
int n,m;
signed main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
int x;
cin>>x;
t[x]++;
}
int cnt=0,ans;
for(int i=1;i<=30000;i++){
if(cnt==m) break;
if(t[i]) cnt++,ans=i;
}
if(cnt==m) cout<<ans;
else cout<<"NO RESULT";
return 0;
}
正确写法
#include<bits/stdc++.h>
#define int long long
using namespace std;
map<int,int> t;
int n,m;
signed main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
int x;
cin>>x;
t[x]++;
}
int cnt=0,ans;
for(int i=1;i<=30000;i++){
if(cnt==m) break;
if(t.find(i)!=t.end()) cnt++,ans=i;
}
if(cnt==m) cout<<ans;
else cout<<"NO RESULT";
return 0;
}
区别
访问 t[i] 的过程:
-
在 \(t\) 中寻找第一关键字 \(i\),找得到跳至步骤3,找不到跳至步骤2;
-
创建新节点,其中第一关键字为 \(i\),第二关键字为 \(0\),跳至步骤3;
-
返回第二关键字,即 t[i] 的值。
访问 t.find(i) 的过程:
-
在 \(t\) 中寻找第一关键字 \(i\),找得到跳至步骤3,找不到跳至步骤2;
-
返回 t.end()。
-
返回 \(t[i]\) 的迭代器。
这时,我们发现访问 t[i] 的过程中,节点数 \(n\) 会变大,所以复杂度偏大。


浙公网安备 33010602011771号