计算 (i, 0) 和 (j, 1) 之间给定线的交点数
给定一个数组, lines[]的N对形式为(i, j)其中(i, j)表示从坐标(i, 0)到(j, 1)的线段,任务是找到给定线的交点。
例子:
Input: lines[] = {{1, 2}, {2, 1}}
Output: 1
Explanation: For the given two pairs, the line form (1, 0) to (2, 1) intersect with the line from (2, 0) to (1, 1) at point (1.5, 0.5). Hence the total count of points of intersection is 1.
Input: lines[] = {{1, 5}, {2, 1}, {3, 7}, {4, 1}, {8, 2}}
Output: 5
方法:给定的问题可以使用基于策略的数据结构的贪心方法来解决。可以观察到,对于表示 b 的线,两对(a, b)和(c, d)相交(a > c and b < d)或(a < c and b > d)必须成立。
因此,使用这个观察,给定的对数组可以按第一个元素的降序排序。在遍历数组时,将第二个元素的值插入基于策略的数据结构中,并使用 order_of_key函数找到小于插入对的第二个元素的元素的计数,并将计数的总和保持在一个变量中。类似地,计算给定数组对以第二个元素的降序排序后的情况。
下面是上述方法的实现:
C++
// C++ Program of the above approach
#include
#include
using namespace __gnu_pbds;
using namespace std;
// Defining Policy Based Data Structure
typedef tree, rb_tree_tag,
tree_order_statistics_node_update>
ordered_multiset;
// Function to count points
// of intersection of pairs
// (a, b) and (c, d)
// such that a > c and b < d
int cntIntersections(
vector > lines,
int N)
{
// Stores the count
// of intersection points
int cnt = 0;
// Initializing Ordered Multiset
ordered_multiset s;
// Loop to iterate the array
for (int i = 0; i < N; i++) {
// Add the count of integers
// smaller than lines[i].second
// in the total count
cnt += s.order_of_key(lines[i].second);
// Insert lines[i].second into s
s.insert(lines[i].second);
}
// Return Count
return cnt;
}
// Function to find the
// total count of points of
// intersections of all the given lines
int cntAllIntersections(
vector > lines,
int N)
{
// Sort the array in decreasing
// order of 1st element
sort(lines.begin(), lines.end(),
greater >());
// Stores the total count
int totalCnt = 0;
// Function call for cases
// with a > c and b < d
totalCnt += cntIntersections(lines, N);
// Swap all the pairs of the array in order
// to calculate cases with a < c and b > d
for (int i = 0; i < N; i++) {
swap(lines[i].first, lines[i].second);
}
// Function call for cases
// with a < c and b > d
totalCnt += cntIntersections(lines, N);
// Return Answer
return totalCnt;
}
// Driver Code
int main()
{
vector > lines{
{1, 5}, {2, 1}, {3, 7}, {4, 1}, {8, 2}
};
cout << cntAllIntersections(lines,
lines.size());
return 0;
}
5
时间复杂度: O(N*log N)
辅助空间: O(N)