2017-05-21
题目大意:
给定N个区间,有重叠部分的区间可以合并成一个区间,求合并后最长的区间长度,和最大的区间间隙(即两个区间之间的间隔)。
题解:
用pair < int, int > 存储所有区间,按照first升序排序,然后合并有重叠部分的区间。再在合并后的区间里找最大的区间长度和区间间隙。
代码:
/*
ID: zachery1
PROG: milk2
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#define cin fin
#define cout fout
using namespace std;
ifstream fin("milk2.in");
ofstream fout("milk2.out");
typedef pair<int, int> P;
vector<P> line;
vector<P> mergedLine;
int N;
void merge() {
int begin = line[0].first, end = line[0].second;
for (int i = 1; i < N; i++) {
if (line[i].first <= end) {
if (line[i].second <= end) continue;
else {
end = line[i].second;
}
}
else {
mergedLine.push_back(make_pair(begin, end));
begin = line[i].first;
end = line[i].second;
}
}
mergedLine.push_back(make_pair(begin, end));
}
void solve() {
int maxMilking, maxIdle;
maxMilking = mergedLine[0].second - mergedLine[0].first;
maxIdle = 0;
for (int i = 1; i < mergedLine.size(); i++) {
maxMilking = max(maxMilking, mergedLine[i].second - mergedLine[i].first);
maxIdle = max(maxIdle, mergedLine[i].first - mergedLine[i-1].second);
}
cout << maxMilking << " " << maxIdle << endl;
}
int main() {
cin >> N;
for (int i = 0; i < N; i++) {
int begin, end;
cin >> begin >> end;
line.push_back(make_pair(begin, end));
}
sort(line.begin(), line.end());
merge();
solve();
return 0;
}