当前位置:网站首页>GYM103660H.Distance
GYM103660H.Distance
2022-07-17 22:30:00 【HeartFireY】
GYM103660H.Distance
题目思路
定义 d i s t ( l , r , x ) dist(l, r, x) dist(l,r,x)为点 x x x到区间 [ l , r ] [l, r] [l,r]的距离(如果包含则距离为 0 0 0)。求 x x x使得 ∑ i = 1 k d i s t ( l i , r i , x ) \sum^k_{i = 1} dist(l_i, r_i, x) ∑i=1kdist(li,ri,x)最小。

不难发现,实际上就是对于给定的一堆区间,寻找一个竖线,使之穿过的区间尽可能地多,且距离未穿过的区间的距离尽可能小。考虑如何处理未穿过的区间:
- 初始我们插入一个区间,此时轴位于区间内,左右堆各插入一个端点;
- 对于新插入的区间,如果右端点比当前左侧最右端更靠左,说明轴应该往左移动,使之穿过新插入的区间;
- 如果新插入的区间,如果左端点比当前右侧最左端更靠右,说明轴应该向右移动,使之穿过新插入的区间;
- 否则,轴不需要移动,因为左右两侧队列处于平衡状态。那么左右端点分别插入左右队列即可。
Code
#include <bits/stdc++.h>
#pragma gcc optimize(2)
#define int long long
#define endl '\n'
using namespace std;
const int N = 1e5 + 10;
priority_queue<int, vector<int>, less<int>> leftq;
priority_queue<int, vector<int>, greater<int>> rightq;
inline void solve(){
int n = 0, ans = 0; cin >> n;
leftq.emplace(-INT_MAX);
rightq.emplace(INT_MAX);
for(int i = 1; i <= n; i++){
int l, r; cin >> l >> r;
if(r < leftq.top()){
ans += leftq.top() - r;
rightq.emplace(leftq.top()); leftq.pop();
leftq.emplace(l), leftq.emplace(r);
} else if(l > rightq.top()){
ans += l - rightq.top();
leftq.emplace(rightq.top()); rightq.pop();
rightq.emplace(l), rightq.emplace(r);
} else {
leftq.emplace(l), rightq.emplace(r);
}
cout << ans << endl;
}
}
signed main(){
ios_base::sync_with_stdio(false), cin.tie(0);
int t = 1; //cin >> t;
while(t--) solve();
return 0;
}
边栏推荐
- 跨域与CORS
- Tianqin Chapter 9 after class exercise code
- Icml2022 | geometric multimodal comparative representation learning
- TDesign CompositionAPI 重构之路
- 见鬼,U盘空间怎么少了,原来是EFI分区搞的鬼,删除它
- session management
- ObjectARX -- implementation of custom circle
- Which company is better in data filling and report presentation? Yixin ABI gives you the answer
- Leetcode 1296. Divide the array into a set of continuous numbers (provide an idea)
- Database SQL Server
猜你喜欢

End repeated development and personalize the login system in twoorthree times
![[Axi] interpret the additional signals of the Axi protocol (QoS signal, region signal, and user signal)](/img/2b/15b3d831bba6aa772ad83f3ac91d23.png)
[Axi] interpret the additional signals of the Axi protocol (QoS signal, region signal, and user signal)

ObjectARX -- implementation of custom circle

UCAS. Deep learning Final examination questions and brief thinking analysis

FPGA(VGA协议实现)

ORA-08103

MySQL index (I)

kube-proxy & Service & Endpoint

揭开服务网格~Istio Service Mesh神秘的面纱

Labview32-bit and 64 bit compatibility
随机推荐
dba
ORA-08103
BigScience 开源 Bloom 的自然语言处理模型
Module 1 job
Leetcode 1296. 划分数组为连续数字的集合(已解决)
2021.07.13 [station B] collapsed like this
Deployment principle
44. Use orienmask for instance segmentation target detection, MNN deployment and ncnn deployment
分布式事务的性能设计
最大堆与堆排序和优先队列
模块1 作业
Cilium & Hubble
A - Trees on the level(树的层序遍历)
国内顶尖专家集聚广州,探讨健康医疗数据安全应用
MySQL installation
Chapter 1 preliminary knowledge
兩種虛擬機的比較
证券账户上买基金安全吗,我要做基金定投
运行时加载 Objective-C
一次函数 T1744 963字符写法