最长连续不重复子串:
(之前写过,但是思路又忘了qvq
#include <iostream>
#include <set>
using namespace std;
const int N = 1e5+10;
int nums[N];
int s[N];
int main(){
int n;
cin>>n;
for(int i = 1;i<=n;i++){
cin>>nums[i];
}
int res = 0;
for(int i = 1,j=1;i<=n;i++){
s[nums[i]]++;
while(s[nums[i]]>1){
s[nums[j]]--;
j++;
}
res = max(res,i-j+1);
}
cout<<res;
return 0;
}
数二进制数中的1
#include<iostream>
using namespace std;
const int N= 1e5+10;
int nums[N];
int main(){
int n ;
cin>>n;
for(int i = 1;i<=n;i++){
cin>>nums[i];
int res = 0;
while(nums[i]){
if(nums[i]&1)res++;
nums[i]>>=1;
}
cout<<res<<' ';
}
return 0;
}
lowbits操作:lowbit(x)返回x的最后一个1:x&-x
这里用这个的话还可以这样写:
#include<iostream>
using namespace std;
const int N= 1e5+10;
int nums[N];
int lowbit(int x)
{
return x&-x;
}
int main(){
int n ;
cin>>n;
for(int i = 1;i<=n;i++){
cin>>nums[i];
int res = 0;
while(nums[i]){
nums[i] -= lowbit(nums[i]);
res++;
}
cout<<res<<' ';
}
return 0;
}
离散化
数的范围大
数的数量比较少
用vector存下标 然后排序去重 再找数求解
例题区间和
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int N = 1e6+10;
typedef pair<int,int> PII;
int s[N],a[N];
vector<int> nums;
vector<PII> query,adds;
int find(int x){
int r = nums.size()-1,l=0;
while(l<r){
int mid = (l+r)>>1;
if(nums[mid]>=x){
r = mid;
}else{
l = mid+1;
}
}
return l+1;
}
int main(){
int n ,m;
cin>>n>>m;
for(int i = 0;i<n;i++){
int x,c;
cin>>x>>c;
adds.push_back({x,c});
nums.push_back(x);
}
for(int i = 0;i<m;i++){
int l,r;
cin>>l>>r;
query.push_back({l,r});
nums.push_back(l);
nums.push_back(r);
}
//排序去重
sort(nums.begin(),nums.end());
nums.erase(unique(nums.begin(),nums.end()),nums.end());
//处理数组
for(auto i : adds){
int x = find(i.first);
a[x] += i.second;
}
//预处理求前缀和
for(int i = 1;i<=nums.size();i++){
s[i] = s[i-1]+a[i];
}
//查询
for(auto i:query){
int l = find(i.first);
int r = find(i.second);
cout<<s[r] - s[l-1]<<endl;
}
return 0;
}
区间和:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int,int> PII;
vector<PII> ranges;
int main() {
int n;
cin>>n;
for(int i = 0;i<n;i++){
int l,r;
cin>>l>>r;
ranges.push_back({l,r});
}
int ans = n;
sort(ranges.begin(),ranges.end());
auto temp = ranges[0];
for(int i = 1;i<n;i++){
auto next = ranges[i];
if(temp.second<next.first)
{
temp = next;
}
else if(temp.second>=next.first&&temp.second>=next.second){
ans--;
} else if(temp.second>=next.first&&temp.second<next.second){
ans--;
temp.second = next.second;
}
}
cout<<ans;
return 0;
}