PAT A1125 Chain the Ropes (25分)

tech2026-01-09  11

前言

传送门

正文

参考题解

#include<iostream> #include<algorithm> #include<vector> #include<queue> using namespace std; /* 题意: 给定一段段的绳子,要求把它们串成一条绳。 每次串连的时候,是把两段绳子对折,再连接在一起。 这样得到的绳子又被当成是另一段绳子,可以再次对折去跟另一段绳子串连。 每次串连后,原来两段绳子的长度就会减半。 思路:为了最后得到的绳子的长度最长,故越长的绳子需要在最后再折叠,因为越开始的 绳子,折叠的次数越多。故可以使用优先队列,定义绳子的越短的优先级越高 */ int main(){ priority_queue<int,vector<int>,greater<int>> q; int n,res=0; cin>>n; for(int i,seg;i<n;i++){ cin>>seg; q.push(seg); } while(q.size()!=1){ int a,b; a=q.top(),q.pop(); b=q.top(),q.pop(); res=a+b>>1; q.push(res); } cout<<res<<endl; return 0; }
最新回复(0)