每个测试案例包括两行:
第一行有1个整数n,表示数组的大小。1<=n <= 10^6。
第二行有n个整数,表示数组元素,每个元素均为int。
第三行有1个整数m,表示接下来有m次查询。1<=m<=10^3。
下面有m行,每行有一个整数k,表示要查询的数。
81 2 3 3 3 3 4 513
4
推荐指数:※※
来源:http://ac.jobdu.com/problem.php?pid=1349
开始使用了map,内存溢出 WA
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<map> using namespace std; int main() { int n,i; while(scanf("%d",&n)!=EOF){ map<int,int> num; int tmp; for(i=0;i<n;i++){ scanf("%d",&tmp); num[tmp]++; } int m; scanf("%d",&m); for(i=0;i<m;i++){ scanf("%d",&tmp); printf("%d\n",num[tmp]); } } return 0; }
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<string.h> using namespace std; int bottom_search(int val,int *num ,int len) { int low=0,high=len; while(low<high){ int mid=low+(high-low)/2; if(num[mid]>val) high=mid-1; else if(num[mid]<val) low=mid+1; else high=mid; } return num[high]==val?high:-1; } int up_search(int val,int *num,int len){ int low=0,high=len; while(low<high){ int mid=low+(high-low)/2; if(num[mid]>val) high=mid-1; else if(num[mid]<=val) low=mid+1; } if(low<len){ if(num[low]!=val) low--; } else low--; return num[low]==val?low:-1; } int count(int val,int *num,int len){ int bottom=bottom_search(val,num,len); int up=up_search(val,num,len); return bottom==-1?0:(up-bottom+1); } int main() { int n,i; while(scanf("%d",&n)!=EOF){ int *num=new int [n]; for(i=0;i<n;i++){ scanf("%d",&num[i]); } int m; scanf("%d",&m); for(i=0;i<m;i++){ int tmp; scanf("%d",&tmp); printf("%d\n",count(tmp,num,n)); } } return 0; }
关于上下界,algorithm 有函数:lower_bound 和upper_bound (AC)
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<vector> #include<algorithm> using namespace std; int count(int val,vector<int > *num){ vector<int >::iterator bottom, up; bottom = lower_bound((*num).begin(),(*num).end(),val); up=upper_bound((*num).begin(),(*num).end(),val); if(bottom==(*num).end()||*bottom!=val) return 0; up--; if(up>=(*num).begin()&&*up==val) return up-bottom+1; return 0; } int main() { int n,i; while(scanf("%d",&n)!=EOF){ vector<int > num; num.resize(n); for(i=0;i<n;i++){ scanf("%d",&num[i]); } int m; scanf("%d",&m); for(i=0;i<m;i++){ int tmp; scanf("%d",&tmp); printf("%d\n",count(tmp,&num)); } } return 0; }