CSU 1588 合并果子
2016-08-24 23:16
211 查看
现在有n堆果子,第i堆有ai个果子。现在要把这些果子合并成一堆,每次合并的代价是两堆果子的总果子数。求合并所有果子的最小代价。
Input
第一行包含一个整数T(T<=50),表示数据组数。
每组数据第一行包含一个整数n(2<=n<=1000),表示果子的堆数。
第二行包含n个正整数ai(ai<=100),表示每堆果子的果子数。
Output
每组数据仅一行,表示最小合并代价。
Sample Input
Sample Output
这题可以用最小生成树去做的,因为数据有点水,所以你也可以每次找了之后排序下,然后重新找,然后再排序下就好了;排序方式最好用插入排序,当我们第一次排序之后再做插入,其实这个数组就其他值都已经是排好序的了,所以用插入排序之后时间效率其实可以达到(On)的;
这里我用的是优先队列来处理,处理起来就简单很多了,只要加入好了优先级就可以了:
#include<queue>
#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;
struct cmp
{
bool operator()(const int a,int b)
const{
return a>b;
}
};
int main()
{
int T,n,a;
cin>>T;
while(T--)
{
priority_queue<int,vector<int>,cmp> pq;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a;
pq.push(a);
}
int x,y,res;
int sum=0;
while(!pq.empty()&&pq.size()!=1)
{
x=pq.top();
pq.pop();
y=pq.top();
res=x+y;
pq.pop();
pq.push(res);
sum+=res;
}
// cout<<endl;
cout<<sum<<endl;
}
return 0;
}
Input
第一行包含一个整数T(T<=50),表示数据组数。
每组数据第一行包含一个整数n(2<=n<=1000),表示果子的堆数。
第二行包含n个正整数ai(ai<=100),表示每堆果子的果子数。
Output
每组数据仅一行,表示最小合并代价。
Sample Input
2 4 1 2 3 4 5 3 5 2 1 4
Sample Output
19 33
这题可以用最小生成树去做的,因为数据有点水,所以你也可以每次找了之后排序下,然后重新找,然后再排序下就好了;排序方式最好用插入排序,当我们第一次排序之后再做插入,其实这个数组就其他值都已经是排好序的了,所以用插入排序之后时间效率其实可以达到(On)的;
这里我用的是优先队列来处理,处理起来就简单很多了,只要加入好了优先级就可以了:
#include<queue>
#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;
struct cmp
{
bool operator()(const int a,int b)
const{
return a>b;
}
};
int main()
{
int T,n,a;
cin>>T;
while(T--)
{
priority_queue<int,vector<int>,cmp> pq;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a;
pq.push(a);
}
int x,y,res;
int sum=0;
while(!pq.empty()&&pq.size()!=1)
{
x=pq.top();
pq.pop();
y=pq.top();
res=x+y;
pq.pop();
pq.push(res);
sum+=res;
}
// cout<<endl;
cout<<sum<<endl;
}
return 0;
}
相关文章推荐
- CSU 1588 合并果子(优先队列)
- CSU-1588 合并果子
- CSU1588 合并果子(贪心)
- CSU 1588 合并果子(贪心 优先队列)
- 1588: 合并果子
- 合并果子
- 【双队列】【NOIP2004提高组】二、合并果子
- NOIP 1199 合并果子终于做出来了…
- Luogu-p1090 合并果子(优先队列)
- 合并果子 (优先队列小根堆)
- P1090 合并果子
- C++合并果子 2004年提高组真题
- tyvj 1066 合并果子(优先队列)
- 合并果子,优先队列的使用
- 合并果子(堆)
- JZOJ 1775. 合并果子2 (Standard IO)
- Luogu 1090 合并果子(贪心,优先队列,STL运用)
- 数据结构----堆----合并果子
- 【堆排】合并果子
- 合并果子-----单调队列