当前位置:网站首页>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();
}
}
边栏推荐
猜你喜欢

GraphQL初识

Systick timer basic learning and hand tearing code

Rip comprehensive experiment

05-中央处理器

樂視還有400多比特員工?過著沒有老板的神仙日子 官方出來回應了...

TCP three handshakes and four disconnects

RHCE ansible second operation

Tools and methods - Excel plug-in xltools

MySQL storage engine details

MySQL master-slave replication + read write separation
随机推荐
【NoSQL】redis高可用和持久化
[MCU simulation] (VII) addressing mode - bit addressing
[single chip microcomputer simulation] (XI) instruction system logic operation instruction - logic and instruction anl, logic or instruction ORL
Nat comprehensive experiment
多项式插值拟合(三)
RHCE ansible second operation
【单片机仿真】(十六)控制转移类指令 — 无条件转移指令、条件转移指令
【单片机仿真】(四)寻址方式 — 寄存器寻址与直接寻址
OpenVINO中的FCOS人脸检测模型代码演示
【PHP】tp6多表连接查询
JPA初识(ORM思想、JPA的基本操作)
GFS distributed file system
當你在Linux系統中編譯安裝MySQL數據庫卡住了怎麼辦?
[MCU simulation] (XXI) dB (define byte) - define byte
[NoSQL] redis master-slave, sentinel, cluster
人脸检测几种方法
ncnn 部分算子不支持的替换操作
多项式插值拟合(二)
Mysql多表查询
05-中央处理器