There's a beach in the first quadrant. And from time to time, there are sea waves. A wave ( x , y ) means the wave is a rectangle whose vertexes are ( 0 , 0 ), ( x , 0 ), ( 0 , y ), ( x , y ). Every time the wave will wash out the trace of former wave in its range and remain its own trace of ( x , 0 ) -> ( x , y ) and ( 0 , y ) -> ( x , y ). Now the toad on the coast wants to know the total length of trace on the coast after n waves. It's guaranteed that a wave will not cover the other completely.
Input
The first line is the number of waves n(n≤50000).
The next n lines,each contains two numbers x y ,( 0<x , y≤10000000 ),the i-th line means the i-th second there comes a wave of ( x , y ), it's guaranteed that when 1≤i , j≤n ,xi≤xj and yi≤yj don't set up at the same time.
Output
An Integer stands for the answer.
Hint:
As for the sample input, the answer is 3+3+1+1+1+1=10
样例输入
3 1 4 4 1 3 3
样例输出
10
题目来源
思路:
既然新加的点会覆盖之前比他短的点,那么我们可以对平行于x轴与y轴的线按倒序维护。
复杂度O( nlogn )
#include <bits/stdc++.h> #include <bits/extc++.h> using namespace std; typedef long long ll; ll height(std::vector<int> v){ int sz=v.size(); set<int>st; ll ans=0; for (int i=sz-1; i>=0; --i){ set<int>::iterator it = st.lower_bound(v[i]); if(it==st.begin()) ans+=v[i]; else { it--; ans+=v[i]-(*it); } st.insert(v[i]); } return ans; } int main(){ // freopen("in.txt","r",stdin); int x,y,n; std::vector<int> xx,yy; while(scanf("%d",&n)==1){ xx.clear(),yy.clear(); while(n--){ scanf("%d%d",&x,&y); xx.push_back(x); yy.push_back(y); } printf("%lld ",height(xx)+height(yy)); } return 0; }