Problem Link
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
struct Order
{
ll s;
ll e;
ll p;
Order(){}
Order(ll s, ll e, ll p)
{
this->s = s;
this->e = e;
this->p = p;
}
bool operator <(const Order &other) const {
return e < other.e;
}
};
int findLastNonConflictingOrder(Order arr[], int index)
{
int start = 0;
int end = index -1;
int result = -1;
while(start <= end)
{
int mid = (start + end) / 2;
if(arr[index].s >= arr[mid].e)
{
result = mid;
start = mid + 1;
}
else
{
end = mid - 1;
}
}
return result;
}
void findMaxProfit(Order arr[], int n)
{
ll dp[n];
dp[0] = arr[0].p;
ll profitInclusive, profitExclusive;
for(int i = 1; i < n; i++)
{
profitInclusive = arr[i].p;
int j = findLastNonConflictingOrder(arr, i);
if(j != -1)
{
profitInclusive += dp[j];
}
profitExclusive = dp[i - 1];
dp[i] = max(profitExclusive, profitInclusive);
}
cout << dp[n - 1] << endl;
}
int main(int argc, char const *argv[])
{
int t, n;
ll s, d, p;
cin >> t;
while(t--)
{
cin >> n;
Order arr[n];
for(int i = 0; i < n; i++)
{
cin >> s >> d >> p;
arr[i] = Order(s, s + d, p);
}
// sort in ascending order of end time
sort(arr, arr + n);
findMaxProfit(arr, n);
}
return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
struct Order
{
ll s;
ll e;
ll p;
Order(){}
Order(ll s, ll e, ll p)
{
this->s = s;
this->e = e;
this->p = p;
}
bool operator <(const Order &other) const {
return e < other.e;
}
};
int findLastNonConflictingOrder(Order arr[], int index)
{
int start = 0;
int end = index -1;
int result = -1;
while(start <= end)
{
int mid = (start + end) / 2;
if(arr[index].s >= arr[mid].e)
{
result = mid;
start = mid + 1;
}
else
{
end = mid - 1;
}
}
return result;
}
void findMaxProfit(Order arr[], int n)
{
ll dp[n];
dp[0] = arr[0].p;
ll profitInclusive, profitExclusive;
for(int i = 1; i < n; i++)
{
profitInclusive = arr[i].p;
int j = findLastNonConflictingOrder(arr, i);
if(j != -1)
{
profitInclusive += dp[j];
}
profitExclusive = dp[i - 1];
dp[i] = max(profitExclusive, profitInclusive);
}
cout << dp[n - 1] << endl;
}
int main(int argc, char const *argv[])
{
int t, n;
ll s, d, p;
cin >> t;
while(t--)
{
cin >> n;
Order arr[n];
for(int i = 0; i < n; i++)
{
cin >> s >> d >> p;
arr[i] = Order(s, s + d, p);
}
// sort in ascending order of end time
sort(arr, arr + n);
findMaxProfit(arr, n);
}
return 0;
}
Comments
Post a Comment