学习:priority_queue 基础类型默认是大根堆,全的写法是priority_queue <int,vector,less >
洛谷:2827
题意过程描述:
(变量sig记录经过时间增加的长度)
- 找到最值
- 切成两半
- 插入新产生的两个值
- sig记录增加的长度
80分代码:
#include <bits/stdc++.h>
using namespace std;
priority_queue <int> ans; //大根堆
int n, m, q, u, v, t, sig;
double p;
int tot;
int main() {
cin >> n >> m >> q >> u >> v >> t;
p = (double) u / v;
int tmp;
for(int i = 1; i <= n; i ++) {
cin >> tmp;
ans.push(tmp);
}
for(int i = 1; i <= m; i ++) { //n只蚯蚓被切
int top = ans.top() + sig; //找到最长的蚯蚓 ,最长的蚯蚓提出来后要加上当前的秒数
ans.pop();
int a1 = floor(p * (double)top), a2 = top - a1; //计算两只蚯蚓的长度
a1 -= sig, a2 -= sig; //存入堆前要减去当前的秒数
a1 -= q, a2 -= q; //再减去这一秒增加的长度
ans.push(a1), ans.push(a2); //两只蚯蚓存入数组
if(i % t == 0) cout << top << " ";
sig += q;
}
cout << endl;
for(int i = 1; !ans.empty(); i ++) {
if(i % t == 0) cout << ans.top() + sig << " ";
ans.pop();
}
return 0;
}
换个思路:
(变量delt记录经过时间增加的长度)
- 排序O(n*logn)
- 用三个堆,分别存放没被切的蚯蚓,被切两半的蚯蚓
- 每一秒,找到3个堆顶的最大值来切O(1)
- 计算切成两半的长度O(1)
- 插入两个新的值O(1)
100分代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 2e7;
const int M = 1e7;
int q1[N], q2[M], q3[M];
int h1, h2, h3, t1 = 1, t2 = 1, t3 = 1;
int n, m, q, u, v, t;
int delta;
int cmp(int z, int zz) {
return z > zz;
}
int main() {
cin >> n >> m >> q >> u >> v >> t;
for(int i = 1, x; i <= n; i ++) cin >> x, q1[t1 ++] = x;
sort(q1 + 1, q1 + 1 + n, cmp);
h1 = h2 = h3 = 1;
for(int i = 1; i <= m; i ++) {
int x = INT_MIN;
if(h1 < t1) x = max(x, q1[h1]); //先判断是否为空
if(h2 < t2) x = max(x, q2[h2]);
if(h3 < t3) x = max(x, q3[h3]);
if(x == q1[h1] && h1 < t1) h1 ++;
else if(x == q2[h2] && h2 < t2) h2 ++;
else h3 ++;
x += delta;
delta += q;
int l = x * 1ll * u / v, r = x - l;//乘的顺序要优先于除 否则会爆int
q2[t2 ++] = l - delta, q3[t3 ++] = r - delta;
if(i % t == 0) {
cout << x << " ";
}
}
cout<<endl;
for(int i = 1; i <= n + m; i ++) {
int x = INT_MIN;
if(h1 < t1) x = max(x, q1[h1]);
if(h2 < t2) x = max(x, q2[h2]);
if(h3 < t3) x = max(x, q3[h3]);
if(x == q1[h1] && h1 < t1) h1++;
else if(x == q2[h2] && h2 < t2) h2++;
else h3 ++;
x += delta;
if(i % t == 0)
cout << x << " ";
}
return 0;
}