Last active 1729868562

Revision 65fec984cc9e2f657af838ff23e3176263941156

q2.cpp Raw
1#include <iostream>
2#include <vector>
3#include <algorithm>
4#include <climits>
5#include<bits/stdc++.h>
6
7using namespace std;
8
9#define ll long long
10
11// Struct to represent a segment with L, R, and cost
12struct Segment {
13 int L, R, cost;
14 Segment(int left, int right, int c) : L(left), R(right), cost(c) {}
15};
16
17// Function to calculate the minimum product of valid non-overlapping segments
18long long findMinCostProduct(const vector<Segment> &segments) {
19 int N = segments.size();
20
21 // Sorting by left endpoint (L)
22 vector<Segment> sortedByL = segments;
23 sort(sortedByL.begin(), sortedByL.end(), [](Segment a, Segment b) {
24 if (a.L != b.L) return a.L < b.L;
25 return a.R < b.R;
26 });
27
28 // Sorting by right endpoint (R)
29 vector<Segment> sortedByR = segments;
30 sort(sortedByR.begin(), sortedByR.end(), [](Segment a, Segment b) {
31 if (a.R != b.R) return a.R < b.R;
32 return a.L < b.L;
33 });
34
35 long long minCostSeen = LLONG_MAX; // Store the minimum cost of valid non-overlapping segments
36 long long minProduct = LLONG_MAX; // Store the minimum product of costs for valid pairs
37
38 int rIndex = 0;
39
40 // Iterate over sortedByL (by left endpoint)
41 for (const Segment &current : sortedByL) {
42 // Check for valid non-overlapping segments (sortedByR's R < current.L)
43 while (rIndex < N && sortedByR[rIndex].R < current.L) {
44 minCostSeen = min(minCostSeen, (long long)sortedByR[rIndex].cost);
45 ++rIndex;
46 }
47
48 // If a valid segment is found, calculate the product of costs
49 if (minCostSeen != LLONG_MAX) {
50 long long product = minCostSeen * (long long)current.cost;
51 minProduct = min(minProduct, product);
52 }
53 }
54
55 // Return the result
56 return (minProduct != LLONG_MAX) ? minProduct : -1; // Return -1 if no valid pair is found
57}
q3.cpp Raw
1int minMoves(vector<int>arr, int n, int k) {
2
3 sort(arr.begin(), arr.end());
4
5 int i = 0, j = n - 1;
6 int moves = 0;
7
8 while (i <= j) {
9
10 if (arr[i] + arr[j] <= k) {
11 i++;
12 }
13
14 j--;
15
16 moves++;
17 }
18
19 return moves;
20}