练习1
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<sstream>
using namespace std;
#define L 101
int heap[L]; //模拟堆
const int N =10;
int b[N+1]={0,3,5,1,7,6,4,2,5,4,1}; //存储输入数据
int tail=0; //指向Last元素
int t=0;
int res=0;
int sum=0;
int x,y;
void put(int n){
heap[++tail] = n;
int now=tail;
int next=now/2; //下->上 :next为父亲
while(now>1){
if(heap[next] <= heap[now]) break;
else{
t=heap[now];
heap[now] = heap[next];
heap[next] = t;
//向上移动节点
now = next;
next = now/2;
}
}
}
int get(){
res = heap[1];
heap[1] = heap[tail--];
int now = 1;
int next = 2*now;
while(next <= tail){
if(next+1 <= tail && heap[next+1] < heap[next]) next++; //右子树更小
if(heap[now]<=heap[next])return res;
else{
t=heap[now];
heap[now] = heap[next];
heap[next] = t;
now = next;
next = now*2;
}
}
return res; //无论如何都要给我return出来!!!!
}
int main()
{
//1.建堆(for + put)
for(int i=1;i<=N;i++){
put(b[i]);
}
//2.Huffman森林
while(tail>1){
x = get();
y = get();
sum += x+y;
put(x+y);
}
cout << sum;
return 0;
}
//cout << "输入:"
练习1 - 合并果子(fruit)
最新推荐文章于 2023-03-28 21:29:07 发布