1. 双指针算法
作用:优化 时间复杂度为O(N) eg1:单词识别:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char str[1000];
gets(str);
int n = strlen(str);
for(int i = 0;i<n;i++)
{
int j = i;
while(j<n&&str[j]!=' ') j++;
for(int k = i;k<j;k++) cout<<str[k];
cout<<endl;
i=j;
}
return 0;
}
eg2:判断数字不重复连续个数
#include <iostream>
#include <string.h>
using namespace std;
const int N = 100010;
int n;
int s[N],a[N];
int main()
{
cin >> n;
for(int i = 0;i<n;i++) cin>>a[i];
int res = 0;
for(int i = 0,j = 0;i<n;i++){
s[a[i]]++;
while(s[a[i]] > 1){
s[a[j]]--;
j++;
}
res = max(res,i-j+1);
}
cout << res <<endl;
return 0;
}
2.位运算
n的二进制第k位是多少? 常用操作:n >> k & 1
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int n = 10;
for(int k = 3;k>=0;k --) cout << (n >> k & 1);
return 0;
}
3.lowbit
lowbit(x)返回x的最后一位1,包括后面的0
C++里 -x为x的补码,-x为取反x+1, 作用:求x的二进制表示里面1的个数
4.整数离散化
模板 eg:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int,int> PII;
const int N = 300010;
int n,m;
int a[N],s[N];
vector<int> alls;
vector<PII> add,query;
vector<int>::iterator unique(vector<int> &a)
{
int j = 0;
for(int i = 0;i < a.size();i++)
if(!i || a[i]!=a[i-1])
a[j++] = a[i];
return a.begin() + j;
}
int find(int x)
{
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 r+1;
}
int main()
{
cin >> n >> m;
for(int i = 0;i<n;i++)
{
int x,c;
cin>> x>> c;
add.push_back({x,c});
alls.push_back(x);
}
for(int i = 0;i < m;i++){
int l,r;
cin >> 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 item : add){
int x = find(item.first);
a[x]+=item.second;
}
for(int i = 1;i<=alls.size();i++) s[i] = s[i-1]+a[i];
for(auto item : query)
{
int l = find(item.first),r = find(item.second);
cout << s[r] - s[l-1] <<endl;
}
return 0;
}
4.区间合并
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef pair<int,int> PII;
const int N = 100010;
int n;
vector<PII> segs;
void merge(vector<PII> &segs)
{
vector<PII> res;
sort(segs.begin(),segs.end());
int st = -2e9,ed = -2e9;
for(auto seg : segs)
if(ed < seg.first)
{
if (st != -2e9) res.push_back({st,ed});
st = seg.first,ed = seg.second;
}
else ed = max(ed,seg.second);
if(st != -2e9) res.push_back({st,ed});
segs = res;
}
int main()
{
cin >> n;
for(int i = 0;i<n;i++)
{
int l,r;
cin >> l >> r;
segs.push_back({l,r});
}
merge(segs);
cout << segs.size() <<endl;
return 0;
}
|