http://acm.fafu.edu.cn/problem.php?id=1266

//fafu oj 1266 数数 //二分,具体看代码 #include <stdio.h> #include <string.h> #include <algorithm> using namespace std; #define N 1000005 int num[N]; int main() { freopen("in.txt", "r", stdin); int n_num, n_query; while(scanf("%d", &n_num) != EOF) { for(int i = 0; i < n_num; ++i) scanf("%d", &num[i]); sort(num, num + n_num); scanf("%d", &n_query); int cnt = 0; for(int i = 0; i < n_query; ++i) { int l = 0, r = n_num - 1; int aim, mid; scanf("%d", &aim); bool is_find = false; while(l <= r) { mid = (l + r) >> 1; if(num[mid] == aim) { is_find = true; while(num[l] < aim) l++; while(num[l] >= aim && l >= 0) l--; while(num[r] > aim) r--; while(num[r] <= aim && r < n_num) r++; cnt++; if(cnt > 1) putchar(' '); printf("%d", r - l - 1); break; } else if(num[mid] < aim) l = mid + 1; else r = mid - 1; } if(is_find == false) { cnt++; if(cnt > 1) putchar(' '); putchar('0'); } } puts(""); } return 0; }