区间判断的map对端点覆盖问题
区间选点
区间问题一般对右端点进行排序并用右端点映射左端点
可以高效判断
wa
区间覆盖了,左端点不是最大值
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
int n;
map<int,int> alls;
int main(){
int res = 0;
int ed = -2e9;
cin >> n;
for(int i = 0;i < n;i ++){
int a,b;
cin >> a >> b;
alls[b] = a;
}
for(auto i : alls){
if(ed < i.second){
res ++;
ed = i.first;
}
}
cout << res;
}
ac
multimap直接存所有
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
int n;
multimap<int,int> alls;
int main(){
int res = 0;
int ed = -2e9;
cin >> n;
for(int i = 0;i < n;i ++){
int a,b;
cin >> a >> b;
alls.insert(pair<int,int>{b,a}); //pair<int,int>{b,a} == make_pair(b,a)
}
for(auto i : alls){
if(ed < i.second){
res ++;
ed = i.first;
}
}
cout << res;
}
或者map + 重合判断
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
int n;
map<int,int> alls;
int main(){
int res = 0;
int ed = -2e9;
cin >> n;
for(int i = 0;i < n;i ++){
int a,b;
cin >> a >> b;
if(alls.find(b) != alls.end()) a = max(a,alls[b]);
alls[b] = a;
}
for(auto i : alls){
if(ed < i.second){
res ++;
ed = i.first;
}
}
cout << res;
}