#include<iostream>
using namespace std;constint N =100010;int n;int q[N], s[N];intmain(){scanf("%d",&n);for(int i =0; i < n; i ++)scanf("%d",&q[i]);int res =0;for(int i =0, j =0; i < n; i ++){
s[q[i]]++;while(j < i && s[q[i]]>1) s[q[j ++]]--;
res =max(res, i - j +1);}
cout << res << endl;return0;}
二、位运算常见的两种操作
求整数 n 的二进制表示中第 k 位数字:n >> k & 1。
注意:这里的 k 是从个位开始算的,例如 n = 8 = 0b1000,此时第0、1、2位数字均为0,第3位数字为1。
解释:先把第 k 位数字移到最后一位,再查看最后一位即可。
返回 n 的最后一位(最低位) 1 :lowbit(n) = n & -n。
注意:这里返回的是一个二进制数。例如 n = 1010,返回的是10;n = 101000,返回的是1000。
解释:在 C++ 里,一个数的负数的二进制表示是原数二进制取反后加一的结果,因此 n & -n = n & (~n +1)。
#include<iostream>
using namespace std;intmain(){int n;scanf("%d",&n);while(n --){int x, s =0;scanf("%d",&x);for(int i = x; i; i -= i &-i) s ++;printf("%d ", s);}return0;}
#include<iostream>#include<vector>#include<algorithm>
using namespace std;typedef pair<int,int> PII;constint N =300010;int n, m;int a[N], s[N];
vector<int> alls;// 储存所有用到的下标值,范围是30万
vector<PII> add, query;// 操作用pair数组存储// 二分:找到第一个大于等于x的数的下标加一值intfind(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;}intmain(){
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;}return0;}