# ZeroJudge - f855: 線段覆蓋長度 加強版 ### 題目連結:https://zerojudge.tw/ShowProblem?problemid=f855 ###### tags: `ZeroJudge` `排序(Sorting)` `掃描線演算法(Sweep Line Algorithm)` ```cpp= #include <iostream> #include <algorithm> using namespace std; struct line { int left, right; bool operator<(const line &other) const { if (this->left != other.left) return this->left < other.left; return this->right < other.right; } void operator=(const line &other) { this->left = other.left; this->right = other.right; } } lines[10000], buffer; int main() { cin.sync_with_stdio(false); cin.tie(nullptr); int number, length; while (cin >> number) { for (int i = 0; i < number; ++i) cin >> lines[i].left >> lines[i].right; sort(lines, lines + number); buffer = lines[0]; length = 0; for (int i = 1; i < number; ++i) { if (lines[i].left <= buffer.right) buffer.right = max(lines[i].right, buffer.right); else { length += buffer.right - buffer.left; buffer = lines[i]; } } cout << (length + buffer.right - buffer.left) << '\n'; } } ```