【洛谷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 }