fix: inclusao-de-subintervalos solutions

This commit is contained in:
2026-05-20 14:45:08 -03:00
parent 3ec1280357
commit 33d87c5809
6 changed files with 195 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
priority_queue<pair<int, int>> pq;
int a, b;
for (int i = 0; i < n; i++) {
cin >> a >> b;
pq.push({-a, b});
}
int count = 0;
int end = -1;
while (!pq.empty()) {
auto [_, e] = pq.top();
pq.pop();
if (e > end) {
count++;
end = e;
}
}
cout << count << endl;
return 0;
}

View File

@@ -0,0 +1,66 @@
#include <bits/stdc++.h>
using namespace std;
bool comp(pair<int, int> &a, pair<int, int> &b) {
if (a.first != b.first) {
return a.first < b.first;
}
return a.second > b.second;
}
bool intersecting(pair<int, int> &a, pair<int, int> &b) {
return a.second >= b.first;
}
int main(){
int n; cin >> n;
vector<pair<int, int>> intervals(n);
for (int i = 0; i < n; i++) {
cin >> intervals[i].first;
cin >> intervals[i].second;
}
sort(intervals.begin(), intervals.end(), comp);
// first sort by start time, if two intervals start at the same time the one with the highest end time comes first
// always include the first interval
// keep track of the last included interval so far
// while there are intervals intersecting with the last included interval take the one with the highest ending value
//
// if there is some intersecting interval check if its end time is greater than the last included interval end time, if so include it and update count, else repeat process from the last intersecting interval
// if no intervals intersect with the last included interval then just process the next interval in order
// in both cases update the count by 1
int curInterval = 1, lastIncludedInterval = 0, count = 1;
while (curInterval < n) { // curInterval holds the first interval thaat was not processed yet
int bestIntersectingInterval = lastIncludedInterval, j = curInterval;
while (j < n && intersecting(intervals[lastIncludedInterval], intervals[j])) {
int bestEndTime = intervals[bestIntersectingInterval].second;
int endTime = intervals[j].second;
if (endTime > bestEndTime) {
bestIntersectingInterval = j;
}
j++;
}
if (bestIntersectingInterval != lastIncludedInterval) {
lastIncludedInterval = bestIntersectingInterval;
count++;
} else {
if (j == n) break; // this interval alredy covers every remaining interval
lastIncludedInterval = j;
count++;
}
if (curInterval == j) curInterval++;
else curInterval = j;
}
cout << count << endl;
return 0;
}