1.审美课
这题如果用string暴力运算的话最后一个测试点会超时,所以要使用位运算。
2进制的输入可以这样:x=(x<<1)+input
x表示将原来的二进制数向右移一位,然后再加上第0位num。
但是不能直接对x用~取反,这样右边为0的位也一起取反了,所以要使用异或运算^,若相同则为0,不同则为1,与每一位都为1的二进数取异或也相当于取反了
#include <iostream>
#include <stdio.h>
#include <map>
using namespace std;
int main() {
int n,m,cnt=0,num,x;
map<int,int> mapper;
scanf("%d%d",&n,&m);
int max_num=(1<<m)-1;
for(int i=0;i<n;++i){
string temp="",verse="";
x=0;
for(int j=0;j<m;++j){
scanf("%d",&num);
x=(x<<1)+num;
}
++mapper[x];
if(mapper[x^max_num]!=0)cnt+=mapper[x^max_num];
}
printf("%d",cnt);
return 0;
}
2.区间k大数查询
memcpy函数用于数组的复制,sort是左闭右开的,所以r要加一
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
bool cmp(int a,int b){
return a>b;
}
int main() {
int N,M;
cin>>N;
int save[1010];
for(int i=1;i<=N;++i){
scanf("%d",&save[i]);
}
cin>>M;
int l,r,k;
for(int i=0;i<M;++i){
int temp[1010];
scanf("%d%d%d",&l,&r,&k);
memcpy(temp,save,sizeof(save));
sort(temp+l,temp+r+1,cmp);
printf("%d\n",temp[l+k-1]);
}
return 0;
}
网友评论