/*二分查找 是否存在那个数 从两端开始往目标逼近*/ boolfindNum(int x, int* a, int n){ int first = 0, last = n - 1, middle; bool found = false; while (!found && first <= last) { middle = (first + last) / 2; if (a[middle] == x) found = true; if (a[middle] > x) last = middle - 1; if (a[middle] < x) first = middle + 1; } return found; } /*找到那个数第一次出现的位置*/ intfindFirst(int x, int* a, int n){ int first = 0, last = n - 1, middle; while (first < last) { middle = (first + last) / 2; if (a[middle] < x) first = middle + 1; else last = middle; } return first; } /*其实上面两个二分搜索可以合并成一个的…… 就是后来懒得改了……*/
/*从那个数的位置开始 计算那个数在有序数组中出现了几次*/ intCountNum(int pos, int x, int* a, int n){ int count = 0; for (int i = pos; i < n; i++) { if (a[i] != x) break;//及时停止 count++; } return count; }
intmain(){ int n; cin >> n; int* arr1 = newint[n + 10];//A int* arr2 = newint[n + 10];//B int* arr3 = newint[n + 10];//C int* arr4 = newint[n + 10];//D for (int i = 0; i < n; i++) { cin >> arr1[i]; cin >> arr2[i]; cin >> arr3[i]; cin >> arr4[i]; } int* a1 = newint[n * n + 10];//A和B → E int* a2 = newint[n * n + 10];//C和D → F int count = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a1[count] = arr1[i] + arr2[j]; a2[count] = (-1) * (arr3[i] + arr4[j]);//这边直接求相反数 count++; } }
sort(a2, a2 + n * n);//要先进行排序
int numCount = 0; for (int i = 0; i < n * n; i++) {//遍历 if (findNum(a1[i], a2, n * n) == true) {//如果有 int first = findFirst(a1[i], a2, n * n);//找到第一次出现的位置 numCount += CountNum(first, a1[i], a2, n * n);//计数 出现几次 求和 } } cout << numCount << endl;