堆核心性质:
父亲节点的值小于等于其所有子孙,那么显而易见的,整棵树中的根节点的值就是最小的。
结合模板题进行理解:合并果子
//手写堆(heap),本题用小根堆
#include<bits/stdc++.h>
using namespace std;
int tot= 0;
int heap[10010];
int n;
void insert(int x)
{
tot++;
heap[tot] = x;
int i = tot;
int j = i / 2;
while ((j > 0) && heap[j] > heap[i] )//有父亲且父亲较大
{
swap(heap[j], heap[i]);
i = i / 2;
j = i / 2;
}
}
int pop()
{
int x = heap[1];
heap[1] = heap[tot];
tot--;
int i = 1;
int j = i * 2;
if (j+1 <= tot && heap[j+1] < heap[j]) j++;//j为两个儿子中的小的那个的下标
while (j <=tot && heap[j] < heap[i])//父亲较大,要换
{
swap(heap[j], heap[i]);
i = j;
j = i * 2;
if (j+1 <= tot && heap[j+1] < heap[j]) j++;
}//自己构建图理解最好
return x;
}
int main()
{
cin >> n;
for(int i = 0; i < n; i++){int x; cin >> x; insert(x);}
int ans = 0;
while(tot >= 2)
{
int a = pop();
int b = pop();
ans += a + b;
insert(a + b);
}
cout << ans;
return 0;
}
时间复杂度允许的话可以跑stl:
注意:
在C++的stl里面,有 priority_queue(优先队列) 来实现它,但是请注意priority_queue默认是个大根堆,如果需要变成小根堆的话可以在定义priority_queue时加参数(参见下面代码),也可也把数取相反数之后放进去。
贪心题:
思路:
如果我们已知团队人数最多为 k k k,那么选 S i S_{i} Si大于等于 k k k的武力值最大的 k k k个人。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100020;
#define LL long long
priority_queue<LL, vector<LL>, greater<LL> > q;
//形如“priority_queue<LL> q”是大根堆,上一行写法是小根堆,注意两个>之间一定要有一个空格
struct ty
{
LL v;
int s;
bool operator < (const ty &a) const{
return s > a.s;
}
}a[maxn];
int main()
{
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i++){ scanf("%lld%d",&a[i].v, &a[i].s); }
sort(a+1, a+n+1);
//按照s从大到小排序,之后就根据这个数组来枚举队伍人数k
LL tmp = 0, ans =0;
//tmp用来存当前还在队伍里面的人的武力值之和,堆里的人就是还在队伍里的人
for(int i = 1; i <= n; i++)
{
tmp += a[i].v; q.push(a[i].v);
while(q.size() > a[i].s)
{
tmp -= q.top();
q.pop();
}
//第i个人加入堆里之后,当前对人数的限制就是p[i].s(之前加入的人都比他的s值大)
//这里就相当于从大到小枚举k
ans = max(ans, tmp);
}
printf("%lld", ans);
return 0;
}
ps: 此文写作思路源于大佬:荷塘涟漪