Go
package main
import (
"bufio"
"fmt"
"os"
"sort"
)
type interval struct {
left, right int
}
type intervals []interval
func (i intervals) Len() int {
return len(i)
}
func (i intervals) Swap(x, y int) {
i[x], i[y] = i[y], i[x]
}
func (i intervals) Less(x, y int) bool {
if i[x].left < i[y].left {
return true
} else if i[x].left > i[y].left {
return false
}
return i[x].right < i[y].right
}
func max(x, y int) int {
if x < y {
return y
}
return x
}
func overlap(x, y interval) bool {
return !(x.right < y.left || y.right < x.left)
}
func main() {
in := bufio.NewReader(os.Stdin)
var n int
fmt.Fscan(in, &n)
s := make(intervals, n)
for i := 0; i < n; i++ {
fmt.Fscan(in, &s[i].left, &s[i].right)
}
sort.Sort(s)
merged := intervals{}
for i := 0; i < len(s); i++ {
last := len(merged) - 1
if last >= 0 && overlap(merged[last], s[i]) {
merged[last].right = max(merged[last].right, s[i].right)
} else {
merged = append(merged, s[i])
}
}
fmt.Println(len(merged))
}
C++
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
using namespace std;
bool overlap(const pair<int, int>& p1, const pair<int, int>& p2) {
return !(p1.second < p2.first || p2.second < p1.first);
}
int main() {
int n;
scanf("%d", &n);
vector<pair<int, int>> intervals(n);
for (int i = 0; i < n; ++i) {
scanf("%d %d", &intervals[i].first, &intervals[i].second);
}
sort(intervals.begin(), intervals.end());
vector<pair<int, int>> merged;
for (int i = 0; i < n; ++i) {
int last = merged.size() - 1;
if (last >= 0 && overlap(merged[last], intervals[i])) {
merged[last].second = max(merged[last].second, intervals[i].second);
} else {
merged.emplace_back(intervals[i]);
}
}
printf("%d\n", merged.size());
return 0;
}