zoukankan      html  css  js  c++  java
  • 【洛谷P1090】合并果子

    合并果子

    题目链接

     

    贪心:每次先合并最小的两堆果子

    用堆实现

     

     1 #include<iostream>
     2 #include<cstdio>
     3 using namespace std;
     4 int heap_size,n;
     5 int heap[30001];
     6 
     7 void swap(int &a,int &b)
     8 {
     9     int t=a;a=b;b=t;
    10 }
    11 
    12 void put(int d)
    13 {
    14     int now,next;
    15     heap[++heap_size]=d;
    16     now=heap_size;
    17     while(now>1)
    18     {
    19         next=now>>1;
    20         if(heap[now]>=heap[next]) return;
    21         swap(heap[now],heap[next]);
    22         now=next;
    23     }
    24 }
    25 
    26 int get()
    27 {
    28     int now,next,res;
    29     res=heap[1];
    30     heap[1]=heap[heap_size--];
    31     now=1;
    32     while(now<<1<=heap_size)
    33     {
    34         next=now<<1;
    35         if(next<heap_size&&heap[next+1]<heap[next]) next++;
    36         if(heap[now]<heap[next]) return res;
    37         swap(heap[now],heap[next]);
    38         now=next;
    39     }
    40     return res;
    41 }
    42 
    43 void work()
    44 {
    45     int i,x,y,ans=0;
    46     cin>>n;
    47     for(i=1;i<=n;i++)
    48     {
    49         cin>>x;
    50         put(x);
    51     }
    52     for(i=1;i<n;i++)
    53     {
    54         x=get();
    55         y=get();
    56         ans+=x+y;
    57         put(x+y);
    58     }
    59     cout<<ans<<endl;
    60 }
    61 
    62 int main()
    63 {
    64     ios::sync_with_stdio(false);
    65     work();
    66     return 0;
    67 }

    手写堆真恶心。。

    STL是个好东西

     1 #include<iostream>
     2 #include<queue>
     3 #include<cstdio>
     4 using namespace std;
     5 
     6 priority_queue<int,vector<int>,greater<int> >h;
     7 
     8 int n,x,ans=0,tmp=0;
     9 
    10 int main() {
    11 
    12     scanf("%d",&n);
    13     for(int i = 1; i <= n; i++) {
    14         scanf("%d",&x);  h.push(x);                           
    15     }    
    16     for(int i = 1; i <= n-1; i++) {
    17         tmp = h.top( );                     
    18         h.pop( );
    19         tmp = tmp+h.top( );                  
    20         h.pop( );
    21         h.push(tmp);                          
    22         ans += tmp;                        
    23     }
    24     printf("%d",ans);       
    25     return 0;
    26 }
  • 相关阅读:
    lucene入门
    ssm框架整合
    springmvc异常处理器和拦截器
    软件测试的策略是什么?
    软件质量保证体系是什么 国家标准中与质量保证管理相关的几个标准是什么?他们的编号和全称是什么?
    • β测试
    • α测试
    • 白盒测试
    黑盒测试
    • 数据库的兼容性
  • 原文地址:https://www.cnblogs.com/yjkhhh/p/8495062.html
Copyright © 2011-2022 走看看