洛谷p1090合并果子(优先队列或堆)

题目链接:https://www.luogu.org/problemnew/show/P1090

分析和思路:

贪心,每次取最小的两个,再插入一个使之有序,可以用优先队列或者堆的方法写。

优先队列

 1 #include <iostream>
 2 #include <string>
 3 #include <algorithm>
 4 #include <iomanip>
 5 #include <vector>
 6 #include <map>
 7 #include <set>
 8 #include <stack>
 9 #include <queue>
10 #include <cstdio>
11 #include <cstring>
12 #include <cmath>
13 using namespace std;
14 typedef long long ll;
15 typedef unsigned long long ull;
16 const int maxn=1e6+5;
17 int vis[maxn];
18 /*struct px
19 {
20     int m;//规则是m小的小! 
21     bool operator<(const px &a)const
22     {
23         return m<a.m;
24     }
25 }tmp;*/
26 struct px
27 {
28     int m;//规则是m大的小! 
29     bool operator<(const px &a)const
30     {
31         return m>a.m;
32     }
33 }tmp;
34 priority_queue<px> que;
35 
36 
37 int main()
38 {
39     ios::sync_with_stdio(false); cin.tie(0);
40     
41     int n;
42     cin>>n;
43     for(int i=1;i<=n;i++)
44     {
45         cin>>tmp.m;
46         que.push(tmp);
47     }
48     
49     int cnt=0;
50     ll s=0;
51     while(cnt<n-1)
52     {
53         int t=que.top().m;
54         que.pop();
55         int tt=que.top().m;
56         que.pop();
57         
58         tmp.m=t+tt;
59         s=s+tmp.m;
60         cnt++;
61         
62         que.push(tmp);
63     }
64     cout<<s<<endl;
65 
66     return 0;    
67 }

猜你喜欢

转载自www.cnblogs.com/redblackk/p/9670276.html