数据特别大,但是有效数没有这么多
就需要离散化
离散化的常用方式有map,set和数组
一维离散化
一维区间离散
传送门
给出n个区间,求最后区间交集的总值
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
const int maxn = 2e4+5;
const int inf = 0x3f3f3f3f;
const double eps = 1e-5;
using namespace std;
int read(){
int x=0,f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}
return f*x;
}
struct node{
int l;
int r;
}p[maxn];
bool cmp(node a,node b){
if(a.l==b.l)return a.r<b.r;
return a.l<b.l;
}
int main(){
int n=read();
int l,r;
for(int i=1;i<=n;i++){
p[i].l=read(),p[i].r=read();
}
sort(p+1,p+1+n,cmp);
int ans = 0;
l = p[1].l,r = p[1].r;
ans += r-l;
for(int i=2;i<=n;i++){
if(p[i].l<=r){//更新新的连续的区间
ans += max(0,p[i].r-r);
r = max(r,p[i].r);
}else{//更新新的非连续的区间
l = p[i].l;
r = p[i].r;
ans += r - l;
}
}
printf("%d
",ans);
return 0;
}
#include <iostream>
#include <cstdio>
#include <map>
using namespace std;
const int maxn=2e5+5;
std::map<int, int> lan;
struct node{
int a;
int b;
}moive[maxn];
int main(){
int n;//n个人
scanf("%d",&n);
for(int i=1;i<=n;i++){
int x;
scanf("%d",&x);
lan[x]++;
}
int m;//电影数
scanf("%d",&m);
for(int i=1;i<=m;i++){
scanf("%d",&moive[i].a);
}
for(int i=1;i<=m;i++){
scanf("%d",&moive[i].b);
}
int ans1=0,ans2=0,pos=1;
for(int i=1;i<=m;i++){
int a=moive[i].a;
int b=moive[i].b;
if(ans1==lan[a]&&ans2<lan[b]){
ans1=lan[a];
ans2=lan[b];
pos=i;
}else if(ans1<lan[a]){
ans1=lan[a];
ans2=lan[b];
pos=i;
}
}
printf("%d
",pos);
return 0;
}
差分离散化
传送门
给出n次操作,每次[l,r]加1,最后求出值为1,2,3...n的点的个数
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <map>
#define ll long long
const int maxn = 2e5+5;
const int inf = 0x3f3f3f3f;
const double eps = 1e-5;
using namespace std;
ll read(){
ll x=0,f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}
return f*x;
}
std::map<ll, ll> ma;
ll ans[maxn];
int main(){
ll n=read();
ll l,r;
for(int i=1;i<=n;i++){
l=read(),r=read();
ma[l]++,ma[r+1]--;
}
std::map<ll, ll>::iterator it;
ll x = 0,p = 0;//x是指,p是下标
// ll dis = 0;//这段长度的值是相同的
for(it=ma.begin();it!=ma.end();it++){
// dis = it->first-p;
ans[x] += it->first-p;
x = it->second + x;
p = it->first;
}
for(int i=1;i<=n;i++){
printf("%lld ",ans[i]);
}
return 0;
}