题目地址:http://ac.jobdu.com/problem.php?pid=1349
每个测试案例包括两行:
第一行有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
#include <stdio.h> typedef struct timesofdata{ int data; int times; }TimesOfData; int Bsearch (TimesOfData hash[], int start, int end, int k){ int mid; while (start <= end){ mid = (start + end) / 2; if (hash[mid].data < k) start = mid + 1; else if (hash[mid].data > k) end = mid - 1; else return hash[mid].times; } return 0; } int main(void){ int n; int input; TimesOfData hash[1000000]; int m; int k; int i; int j; int pre; int flag; while (scanf ("%d", &n) != EOF){ for (i=0, j=-1; i<n; ++i){ scanf ("%d", &input); if (i == 0 || input != pre){ ++j; hash[j].data = input; hash[j].times = 1; pre = input; } else{ ++hash[j].times; } } scanf ("%d", &m); while (m-- != 0){ scanf ("%d", &k); printf ("%d\n", Bsearch (hash, 0, j, k)); } } return 0; }
#include <stdio.h> int Bsearch (int data[], int start, int end, int k){ int mid; while (start <= end){ mid = (start + end) / 2; if (data[mid] < k) start = mid + 1; else if (data[mid] > k) end = mid - 1; else return mid; } return -1; } int main(void){ int n; int input[1000000]; int m; int k; int i; int index; int num; while (scanf ("%d", &n) != EOF){ for (i=0; i<n; ++i){ scanf ("%d", &input[i]); } scanf ("%d", &m); while (m-- != 0){ scanf ("%d", &k); index = Bsearch (input, 0, n-1, k); if (index == -1) printf ("0\n"); else{ num = 1; i = index - 1; while (i >= 0 && input[i--] == k) ++num; i = index + 1; while (i < n && input[i++] == k) ++num; printf ("%d\n", num); } } } return 0; }