Cod sursa(job #2911526)

Utilizator matthriscuMatt . matthriscu Data 30 iunie 2022 12:12:27
Problema Heavy metal Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.93 kb
#include <bits/stdc++.h>
using namespace std;

#define NMAX 100005
#define problem "heavymetal"

int main()
{
	freopen(problem ".in", "r", stdin);
	freopen(problem ".out", "w", stdout);

	int n;
	scanf("%d", &n);

	pair<int, int> v[NMAX];

	for (int i = 0; i < n; ++i)
		scanf("%d%d", &v[i].first, &v[i].second);

	sort(v, v + n, [](pair<int, int>& a, pair<int, int>& b) {
		if (a.second == b.second)
			return a.first < b.first;
		return a.second < b.second;
	});

	int dp[NMAX], max_step;
	dp[0] = v[0].second - v[0].first;

	for (max_step = 1; max_step < n; max_step <<= 1);

	for (int i = 1; i < n; ++i) {
		int step = max_step, index = 0;

		for (; step; step >>= 1)
			if (index + step < i && v[index + step].second <= v[i].first)
				index += step;

		if (v[index].second <= v[i].first)
			dp[i] = max(dp[index] + v[i].second - v[i].first, dp[i - 1]);
		else
			dp[i] = max(v[i].second - v[i].first, dp[i - 1]);
	}

	printf("%d\n", dp[n - 1]);
}