#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