在C++中查找数组中满足x^y > y^x的(x, y)对的数量
假设我们有两个正整数数组X和Y。找出满足x^y > y^x的(x, y)对的数量,其中x是X的元素,y是Y的元素。例如,如果X = [2, 1, 6],Y = [1, 5],则输出为3。因为存在三对:(2, 1), (2, 5) 和 (6, 1)
我们可以用一种高效的方法解决这个问题。逻辑很简单,当y > x时,x^y > y^x,但有一些例外情况。这就是技巧所在。
对数组Y进行排序
对于X中的每个元素x,我们必须在Y中找到大于x的最小数字的索引。我们将使用二分查找来实现。或者我们也可以使用upper_bound()函数。
找到的索引之后的所有数字都满足关系,因此只需将它们添加到计数中。
示例
#include <iostream>
#include <algorithm>
using namespace std;
int count(int x, int Y[], int n, int no_of_y[]) {
if (x == 0)
return 0;
if (x == 1)
return no_of_y[0];
int* index = upper_bound(Y, Y + n, x);
int ans = (Y + n) - index;
ans += (no_of_y[0] + no_of_y[1]);
if (x == 2)
ans -= (no_of_y[3] + no_of_y[4]);
if (x == 3)
ans += no_of_y[2];
return ans;
}
int howManyPairs(int X[], int Y[], int m, int n) {
int no_of_y[5] = {0};
for (int i = 0; i < n; i++)
if (Y[i] < 5)
no_of_y[Y[i]]++;
sort(Y, Y + n);
int total_pairs = 0;
for (int i=0; i< m; i++)
total_pairs += count(X[i], Y, n, no_of_y);
return total_pairs;
}
int main() {
int X[] = {2, 1, 6};
int Y[] = {1, 5};
int m = sizeof(X)/sizeof(X[0]);
int n = sizeof(Y)/sizeof(Y[0]);
cout << "Total pair count: " << howManyPairs(X, Y, m, n);
}输出
Total pair count: 3
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP