题目链接:点击这里
解题思路:
本题如果倒着做,那么问题就变得十分简单,当插入一个点时,去找它的右边最近的一个点和左边最近的一个点,此点被这两个点夹在中间,那么它的贡献一定只受限于这两个点,所以用set维护一下很容易就能做。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mx = 1e5 + 10;
struct node
{
int first,second;
bool operator < (node A)const
{
if(first==A.first) return second < A.second;
return first < A.first;
}
};
set <node> st;
int a[mx],b[mx];
int main()
{
int n;
while(~scanf("%d",&n))
{
ll ans = 0;
for(int i=0;i<n;i++) scanf("%d%d",a+i,b+i);
for(int i=n-1;i>=0;i--)
{
node pa = {a[i],b[i]};
auto it = st.lower_bound(pa);
if(!st.size()) ans += a[i]+b[i];
else{
if(it==st.end()) ans += b[i];
else ans += (b[i]-(it->second));
if(it==st.begin()) ans += a[i];
else{
it--;
ans += (a[i]-(it->first));
}
}
st.insert(pa);
}
printf("%lld\n",ans);
}
return 0;
}