Trace
Output
An Integer stands for the answer.
Hint:
As for the sample input, the answer is 3+3+1+1+1+1=103+3+1+1+1+1=10
题目来源
n个浪打上沙滩,(x,y)代表浪会打湿沙滩形成坐标(0,0),(x,0),(x,y),(0,y)的矩形,后打的浪会覆盖一部分之前的浪,但是确保不会完全覆盖(即某一个浪x比之前浪的x大的话,y一定比之前浪的y小,y大则x小),求浪痕迹的总长度
由于之后的浪会覆盖之前的浪,所以从后往前推比较容易,很容易可以看出,对于某个浪,之后的浪如果x比自己大,那么就会覆盖一部分y
所以求法:对于每个浪 ans+=(y - 之后的浪中x比自己大的最大y),x同理
但是暴力求是会超时的,看题解发现大佬们用树状数组或者线段树可以求出来(先留个坑,可能有朝一日回来补)
如果转换一下思路会变得很简单,由于浪之间确保了不会完全覆盖,那么之后的浪中x比自己大的,y肯定比自己小
则求法可变为:对于每个浪ans+=(y - 之后的浪中y比自己小的最大y),x同理
这样一来,就可以用set的自动排序和lower_bound(y)返回>=y的第一个数的位置找到y在集合中的位置,进而找到比自己小的最大的y的位置(-1)
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<fstream>
#include<math.h>
#include<stack>
#include<queue>
#include<bitset>
#include<utility>
#include<set>
#include<map>
#define INF 0x7f7f7f7f
using namespace std;
typedef long long ll;
const int N=50005;
const ll mod=1000000007;
int n;
set<int> sx;
set<int> sy;
int x[N];
int y[N];
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d%d",&x[i],&y[i]);
}
ll ans=0;
sx.insert(0);
sy.insert(0);
set<int>::iterator mx,my;
for(int i=n;i>=1;i--){
sx.insert(x[i]);
sy.insert(y[i]);
mx=sx.lower_bound(x[i]);
mx--;
my=sy.lower_bound(y[i]);
my--;
ans+=(x[i]-*mx);
ans+=(y[i]-*my);
}
printf("%lld\n",ans);
return 0;
}