# [hihoCoder] #1305 : 区间求差 解题报告

### 输出

3 2
2 5 4 10 14 18
1 3 8 15

8

/*************************************************************************
> File Name: seg.cpp
> Author: Maoting Ren
> Mail: mren@g.clemson.edu
> Created Time: Sun 22 May 2016 02:29:16 AM EDT
************************************************************************/

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

vector<pair<int, int> > merge(vector<pair<int, int> >& nums)
{
vector<pair<int, int> >  result;
int len = nums.size(), begin = nums[0].first, end = nums[0].second;
for(int i =1; i< len; i++)
{
if(nums[i].first <= end) end = max(end, nums[i].second);
else
{
result.push_back(make_pair(begin, end));
begin = nums[i].first;
end = nums[i].second;
}
}
result.push_back(make_pair(begin, end));
return result;
}

int main()
{
int N, M, val1, val2;
cin>> N >> M;
vector<pair<int, int> > A(N), B(M);
for(int i =0; i< N; i++)
{
cin>>val1 >> val2;
A[i] = make_pair(val1, val2);
}
for(int i =0; i< M; i++)
{
cin>>val1 >> val2;
B[i] = make_pair(val1, val2);
}
sort(A.begin(), A.end());
sort(B.begin(), B.end());
vector<pair<int, int> > vecA = merge(A);
vector<pair<int, int> > vecB = merge(B);
int begin, end, ans = 0, k =0, lenA = vecA.size(), lenB = vecB.size();

for(int i = 0; i < lenA; i++)
{
int sum = 0;
begin = vecA[i].first, end = vecA[i].second;
while(k < lenB && vecB[k].second <= begin) k++;
while(k < lenB && vecB[k].second > begin && vecB[k].first < end)
{
sum += min(end, vecB[k].second) - max(begin, vecB[k].first);
k++;
}
if(k >0 && vecB[k-1].second > end) k--;
ans += end-begin - sum;
}
cout << ans << endl;
return 0;
}

#### hihocoder 1305 区间求差(经典问题)

2017-05-29 22:25:58

#### 152周 区间求差

2017-06-01 20:03:49

#### hihocoder 1305 区间求差 经典思维+技巧

2017-06-04 16:57:24

#### 区间求差 hihocoder 1305

2017-10-21 21:11:57

#### hihocoder1305(打标记)

2017-05-29 17:50:01

#### hihoCoder 47周 拓扑排序

2015-05-29 00:50:22

#### 1305：整数排序

2017-09-05 16:20:56

#### HihoCoder ——1305

2017-10-16 21:52:18

#### hihoCoder太阁最新面经算法竞赛题解(1)

2017-06-20 20:43:43

#### hihoCoder太阁最新面经算法竞赛题解(6)

2017-06-24 17:02:28