双指针算法
- 双指针算法就是利用两个指针将o( n 2 n^2 n2)的算法进行优化。
- 基本模板如下:
for(int i=0,j=0;i<n;i++){
while(j<i&&check(i,j))j++;
//算法的内容。
}
例如:最长连续子序列问题
for(int i=0,j=0;i<n;i++){
b[a[i]]++;
while(b[a[i]]>1){//通过j指针使相同的数变成只有a[i].
b[a[j]]--;
j++;
}
}
位运算
- n二进制表示中第k位是几
n右移k,看各位是几,即x&1; - 返回x最后一位1,x&-x;
离散化
一个数组个数比较少,但数很大,就是将它映射到一个个数较少的数组,这个过程就是离散化。
1.排序
2.去重;可以用unique函数alls.sort(); slls.erase(unique(begin(),end()),end());
模板题代码
#include<bits/stdc++.h>
using namespace std;
const int N = 3e5+10;
typedef pair<int,int> PII;
vector<int> alls;
vector<PII> add,query;
int n,m;
int a[N],s[N];
int find(int x){//将数据映射到1-alls.size(),方便前缀和操作。
int l = 0,r = alls.size()-1;
while(l<r){
int mid = l+r>>1;
if(alls[mid]>=x) r = mid;
else l = mid + 1;
}
return l+1;
}
int main()
{
scanf("%d%d",&n,&m);
int x,c;
while(n--){
scanf("%d%d",&x,&c);
add.push_back({x,c});
alls.push_back(x);
}
int l,r;
while(m--){
scanf("%d%d",&l,&r);
query.push_back({l,r});
alls.push_back(l);
alls.push_back(r);
}
sort(alls.begin(),alls.end());
alls.erase(unique(alls.begin(),alls.end()),alls.end());
for(auto t : add){
int x = find(t.first);
a[x] += t.second;
}
for(int i=1;i<=alls.size();i++) s[i] = s[i-1]+a[i];
for(auto t : query){
int l = find(t.first),r = find(t.second);
printf("%d\n",s[r]-s[l-1]);
}
return 0;
}
区间合并
模板题代码
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int>PII;
vector<PII> alls;
int n;
int main()
{
scanf("%d",&n);
int l,r;
while(n--){
scanf("%d%d",&l,&r);
alls.push_back({l,r});
}
sort(alls.begin(),alls.end());
vector<PII>res;
int st = -2e9,ed = -2e9;
for(auto t : alls){
if(ed<t.first){
if(st!=-2e9)res.push_back({st,ed});
st = t.first,ed = t.second;
}
else{
ed = max(t.second,ed);
}
}
if(st!=-2e9)res.push_back({st,ed});
printf("%d\n",res.size());
return 0;
}