Then next N lines, each line contains one number a[i](1 ≤ a[i] ≤ 50000) means a[i] units of the i-th meat.
Input The first line is a number N (1 ≤ N ≤ 20000) identified the number of small meat.
Then next N lines, each line contains one number a[i](1 ≤ a[i] ≤ 50000) means a[i] units of the i-th meat.
Output
The minimum number of the energy.
Sample Input 3 8 5 8 Sample Output 34
一开始看完这个题就当做是石子合并类的题了,先排个序然后直接往上加,结果就是收获了一堆wa→_→后来才发现这种做法不行,这题也是比完赛之后才明白的怎么做。直接贪心处理,把这些数进行排序,然后从最小的两个合并,再进行排序,再合并最小的两个,以此类推直到所有的合并在了一起。就相当于把切肉的这个过程给倒过来运行了。
要注意的有两点,一开始我是每一遍循环都sort了一下,然后就TLE了,所以优化了一下,只sort一次,然后里面排序直接排合并的那个数就可以了。另外就是要用long long来处理这道题。
下面是AC代码:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; long long a[20005]; int cmp(long long a,long long b) { return a>b; } int main() { int n; int i,j; long long ans; long long t; while(scanf("%d",&n)!=EOF) { ans=0; for(i=0;i<n;i++) { scanf("%lld",&a[i]); } sort(a,a+n,cmp); for(i=0;i<n-1;i++) { for(j=n-i-1;j>0;j--) { if(a[j]>a[j-1]) { t=a[j]; a[j]=a[j-1]; a[j-1]=t; } else break; } a[n-i-2]=a[n-i-1]+a[n-i-2]; ans+=a[n-i-2]; } cout<<ans<<endl; } return 0; }