构建最优二叉树
作者:互联网
#include<iostream> #include<stdio.h> #include<queue> using namespace std; int main() { priority_queue<int, vector<int>, greater<int> > minHeap; cout<<"请输入各个结点的权重:"; int item; while(cin>>item) { minHeap.push(item); if(getchar()=='\n'){ //判断回车语句应该放在while里的最后,防止输入的最后一个元素取不到 break; } } int first,second,ans=0; while(minHeap.size()>1) { first=minHeap.top(); minHeap.pop(); second=minHeap.top(); minHeap.pop(); minHeap.push(first+second); ans=ans+(first+second); } cout<<"最优二叉树的路径长度:"<<ans<<endl; return 0; } //请输入结点个数:4 //请输入各个结点的权重:7 5 2 4 //最优二叉树的路径长度:35
标签:cout,second,构建,二叉树,ans,minHeap,最优,include,first 来源: https://www.cnblogs.com/zzyf/p/13392583.html