当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
[email protected]之moveActivityIdTo任务回退特殊案例分析"/>学习记录[email protected]之moveActivityIdTo任务回退特殊案例分析

Deployment principle

session management

中断的分类

兩種虛擬機的比較

Notes on random nodes of force buckle 382 linked list

Leetcode 1275. 找出井字棋的獲勝者

CSRF protection mechanism

How to quickly realize Zadig single sign on on authoring?

国科大.深度学习.期末复习知识点总结笔记
随机推荐
[flask introduction series] exception handling
Can [C language - user defined type] be adjusted like this?
Leetcode 1296. Divide the array into a set of continuous numbers (provide an idea)
ZABBIX realizes the monitoring of redis
Classification of interrupts
44. Use orienmask for instance segmentation target detection, MNN deployment and ncnn deployment
Which company is better in data filling and report presentation? Yixin ABI gives you the answer
Labview32-bit and 64 bit compatibility
定时任务,vim直接创建修改用户
High performance pxie data preprocessing board based on kinex ultrascale series FPGA (ku060 +fmc sub card interface)
2021.07.13 [station B] collapsed like this
Leetcode 1296. 划分数组为连续数字的集合(提供一种思路)
P1004 [NOIP2000 提高组] 方格取数
最大堆与堆排序和优先队列
[port 3000 is already in use, solution to the problem of 3000 port being occupied]
国内顶尖专家集聚广州,探讨健康医疗数据安全应用
Read the paper: temporary graph networks for deep learning on dynamic graphs
3438. 数制转换
Gradle introduction notes
TDesign CompositionAPI 重构之路