蒜头君手上有个长度为 nnn 的数组 AAA。由于数组实在太大了,所以蒜头君也不知道数组里面有什么数字,所以蒜头君会经常询问在数组 AAA 中,等于 xxx 的数字有多少个?
输入格式
第一行输入两个整数 nnn 和 mmm,分别表示数组的长度和查询的次数。
接下来一行有 nnn 个整数 aia_iai。
接下来 mmm 行,每行有 111 个整数 xxx,表示蒜头君询问的整数。
输出格式
对于每次查询,输出一个整数,表示数组 AAA 中有多少个 xxx。
数据范围
1≤n,m≤105,0≤x≤1061 \le n, m \le 10^5, 0 \le x \le 10^61≤n,m≤105,0≤x≤106。
Sample Input
10 5 1 1 1 2 3 5 5 7 8 9 0 1 4 9 10
Sample Output
0 3 0 1 0
#include<stdio.h>
#include<iostream>
#include<algorithm>
#define N 100010
using namespace std;
int binarysearch(int a[],int low,int high,int x)
{
while(low+1!=high)
{
int mid=(low+high)/2;
if(a[mid]>=x)
high=mid;
else if(a[mid]<x)
low=mid;
}
return high;//根据情况需求返回low或者high
}
int main()
{
int a[N]={-1};
int i,n,m,x,num,sum=0;
int low,high,mid;
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
sort(a+1,a+n+1);
while(m--)
{
low=0;high=n+1;
scanf("%d",&x);
num=binarysearch(a,low,high,x);
while(a[num]==x)
{
sum++;
num++;
}
printf("%d\n",sum);
sum=0;
}
return 0;
}
在一个非降序列中,查找与蒜头君的给定值最接近的元素。
输入格式
第一行包含一个整数 nn,为非降序列长度。1 \le n \le 1000001≤n≤100000。
第二行包含 nn 个整数,为非降序列各元素。所有元素的大小均在 0\sim1,000,000,0000∼1,000,000,000 之间。
第三行包含一个整数 mm,为要询问的给定值个数。1 \le m \le 100001≤m≤10000。
接下来 mm 行,每行一个整数,为要询问最接近元素的给定值。所有给定值的大小均在 0\sim 1,000,000,0000∼1,000,000,000 之间。
输出格式
mm 行,每行一个整数,为最接近相应给定值的元素值,保持输入顺序。若有多个值满足条件,输出最小的一个。
Sample 1
Inputcopy | Outputcopy |
---|---|
3 2 5 8 2 10 5 | 8 5 |
#include<algorithm>
#include<iostream>
#include<math.h>
#include<set>
using namespace std;
const long long N=100100;
int main()
{
set<long long>sum;
set<long long>::iterator z;//迭代器
// set<long long>::iterator y;
long long a[N],n,m,i,t,j,b,c,x,y;
cin>>n;
for(i=0;i<n;i++)
{
cin>>a[i];
sum.insert(a[i]);
}
cin>>m;
while(m--)
{
cin>>t;
if(t>a[n-1])
cout<<a[n-1]<<endl;
else
{
x=*(sum.lower_bound(t));
z=sum.lower_bound(t);//迭代器
z--;
y=*(z);
b=abs(x-t);
c=abs(y-t);
if(b<c)
cout<<x<<endl;
else
cout<<y<<endl;
}
}
return 0;
}