这里是代码:
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
class line {
public:
long long begin;
long long end;
bool operator < (const line& other) const {
return begin < other.begin;
}
bool if_one(const line& x, const line& y);
void hebing(line& x, line& y);
};
bool line::if_one(const line& x, const line& y)
{
if (x.end >= y.begin)
return true;
else
return false;
}
void line::hebing(line& x, line& y)
{
if (if_one(x, y))
{
x.end = max(y.end, x.end);
y.begin = 0;
y.end = 0;
}
}
line lines[20000];
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> lines[i].begin;
cin >> lines[i].end;
}
sort(lines, lines + n);
for (int i = 0; i < n - 1; i++)
{
if (lines[i].begin < lines[i].end)
{
lines[i].hebing(lines[i], lines[i + 1]);
swap(lines[i], lines[i + 1]);
}
}
long long length = 0;
for (int i = 0; i < n; i++)
{
length += lines[i].end - lines[i].begin;
}
cout << length;
return 0;
}