ZOJ Monthly, March 2018 Easy Number Game【贪心】

The bored BaoBao is playing a number game. In the beginning, there are  numbers. For each turn, BaoBao will take out two numbers from the remaining numbers, and calculate the product of them.

Now, BaoBao is curious to know the minimum sum of the products if he plays at least  turns. Can you tell him?

Input

The first line of input contains a positive integer  (about 30), the number of test cases. For each test case:

The first line contains two integers  and  (). Their meanings are described above.

The second line contains  integers  (), indicating the numbers.

Output

For each test case output one integer, indicating the minimum sum of the products.

Sample Input

3
4 2
1 3 2 4
3 1
2 3 1
4 0
1 3 2 4

Sample Output

10
2
0

Hint

For the first sample test case, the answer is 1 × 4 + 3 × 2 = 10.

For the second sample test case, the answer is 2 × 1 = 2.

每次选取最小的m个,并且从两边开始相乘并求和

 1 #include<iostream>
 2 using namespace std;
 3 #include<cstdio>
 4 #include<cstring>
 5 #include<algorithm>
 6 #include<vector>
 7 typedef long long ll;
 8 vector<ll> a;
 9 int main(){
10     int t;
11     void deal();
12     scanf("%d",&t);
13     while(t--){
14         deal();
15     }
16     return 0;
17 }
18 void deal(){
19     int n,m;
20     scanf("%d%d",&n,&m);
21     a.clear();
22     for(int i=0;i<n;i++){
23         ll p;
24         scanf("%lld",&p);
25         a.push_back(p);
26     }
27     sort(a.begin(),a.end());
28     ll zans = 0;
29     int l = 0;
30     int r = 2*m-1;
31     for(int i=0;i<m&&l<r;i++){
32         zans = zans + a[l]*a[r]; 
33         l += 1;
34         r -= 1;
35     }
36     printf("%lld\n",zans);
37 }

 

posted @ 2018-03-10 17:20  晓风微微  阅读(509)  评论(0编辑  收藏  举报