当前位置:网站首页>D. Permutation Restoration(贪心/双指针/set)
D. Permutation Restoration(贪心/双指针/set)
2022-07-17 00:40:00 【罗gkv】
题意
给定长度为n的排列a[i],令b[i]=i/a[i](向下取整),现给定b[i],求还原出原来的a[i]。
如果有多组解,输出任意一组,题目保证数据至少存在一组解。
思路
因为 b [ i ] = i / a [ i ] b[i]=i/a[i] b[i]=i/a[i](向下取整),所以
a [ i ] ∗ b [ i ] < = i < a [ i ] ∗ ( b [ i ] + 1 ) a[i]*b[i]<= i < a[i]*(b[i]+1) a[i]∗b[i]<=i<a[i]∗(b[i]+1),所以
i / ( b [ i ] + 1 ) < a [ i ] < = i / b [ i ] i/(b[i]+1)< a[i]<=i/b[i] i/(b[i]+1)<a[i]<=i/b[i]
又因为a[i]是排列,我们可以从小到大枚举每个数,同时维护 包含当前数的区间;
每次选取区间时,选择最早过期的,即右区间最小的那个。
结合代码理解
代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 500010;
int n, m;
int a[maxn], b[maxn];
void solve() {
scanf("%d", &n);
vector<pair<int, int> > ve;
for (int i = 1; i <= n; ++i) {
scanf("%d", &b[i]);
ve.push_back(make_pair(i/(b[i]+1)+1, i));
}
// 区间左下标,从小到大排序
sort(ve.begin(), ve.end());
// for (auto v: ve) {
// printf("{%d %d}\n", v.first, v.second);
// }
set<pair<int, int> > st;
for (int i = 1, j = 0; i <= n; ++i) {
// 将包含数i的区间塞进集合
while (j < n && ve[j].first <= i) {
int pos = ve[j].second;
if(b[pos])
st.insert(make_pair(pos/b[pos], pos));
else
st.insert(make_pair(n, pos));
++j;
}
// debug
if (st.empty()) {
printf("%d corrupt\n", i);
break;
}
// 从集合里边选取右边界最小的
a[st.begin()->second] = i;
st.erase(st.begin());
}
for (int i = 1; i <= n; ++i) {
printf("%d ", a[i]);
}
printf("\n");
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
solve();
}
}
边栏推荐
- [PHP] tp6 multi table connection query
- 【单片机仿真】(四)寻址方式 — 寄存器寻址与直接寻址
- [MCU simulation] (XXI) dB (define byte) - define byte
- LETV has more than 400 employees? Living a fairy life without a boss, the official responded
- [single chip microcomputer simulation] (XII) instruction system logic operation instruction - logic XOR instruction XRL, accumulator clear 0 and reverse instruction
- BiSeNetV2-面部分割 ncnn推理
- C language foundation day4 array
- Rip comprehensive experiment
- BiSeNetV1 面部分割
- Rsync - remote synchronization
猜你喜欢

What happens when you get stuck compiling and installing MySQL database in Linux system?

C语言基础Day4-数组

PyTorch最佳实践和代码模板

人脸关键点检测

ncnn param文件及bin模型可视化解析

Multi layer packet structure and TCP triple handshake

ELK日志分析系统

rsync—远程同步

3. Asynctool framework principle source code analysis

RHCE ansible second operation
随机推荐
【单片机仿真】(六)寻址方式 — 变址寻址与相对寻址
一个优酷VIP会员帐号可以几个人用的设备同时登录如何共享多人使用优酷会员账号?
GFS distributed file system
[MCU simulation] (XX) org - set start address
First blog ----- self introduction
【单片机仿真】(十七)控制转移类指令 — 调用及返回指令
DDD 超越 MVC了吗
ncnn DataReader&Extractor&blob
[MCU simulation] (XVIII) control transfer instructions - empty operation instructions
快照:数据快照(数据兜底方式)
重写equals为什么要重写hashcode
【单片机仿真】(一)Proteus8.9 安装教程
[MCU simulation] (I) proteus8.9 installation tutorial
工具及方法 - Excel插件XLTools
while 循环
PyTorch最佳实践和代码模板
[MCU simulation] (II) keil installation tutorial
Redis' simple dynamic string SDS
【NoSQL】redis主从、哨兵、集群
Understand JVM garbage collection in one article