#include #include #include #include #include using namespace std; #define ll long long // Struct to represent a segment with L, R, and cost struct Segment { int L, R, cost; Segment(int left, int right, int c) : L(left), R(right), cost(c) {} }; // Function to calculate the minimum product of valid non-overlapping segments long long findMinCostProduct(const vector &segments) { int N = segments.size(); // Sorting by left endpoint (L) vector sortedByL = segments; sort(sortedByL.begin(), sortedByL.end(), [](Segment a, Segment b) { if (a.L != b.L) return a.L < b.L; return a.R < b.R; }); // Sorting by right endpoint (R) vector sortedByR = segments; sort(sortedByR.begin(), sortedByR.end(), [](Segment a, Segment b) { if (a.R != b.R) return a.R < b.R; return a.L < b.L; }); long long minCostSeen = LLONG_MAX; // Store the minimum cost of valid non-overlapping segments long long minProduct = LLONG_MAX; // Store the minimum product of costs for valid pairs int rIndex = 0; // Iterate over sortedByL (by left endpoint) for (const Segment ¤t : sortedByL) { // Check for valid non-overlapping segments (sortedByR's R < current.L) while (rIndex < N && sortedByR[rIndex].R < current.L) { minCostSeen = min(minCostSeen, (long long)sortedByR[rIndex].cost); ++rIndex; } // If a valid segment is found, calculate the product of costs if (minCostSeen != LLONG_MAX) { long long product = minCostSeen * (long long)current.cost; minProduct = min(minProduct, product); } } // Return the result return (minProduct != LLONG_MAX) ? minProduct : -1; // Return -1 if no valid pair is found }