B. Olya and Game with Arrays
time limit per test
1 second
memory limit per test
256 megabytes
Artem suggested a game to the girl Olya. There is a list of nn arrays, where the ii-th array contains mi≥2mi≥2 positive integers ai,1,ai,2,…,ai,miai,1,ai,2,…,ai,mi.
Olya can move at most one (possibly 00) integer from each array to another array. Note that integers can be moved from one array only once, but integers can be added to one array multiple times, and all the movements are done at the same time.
The beauty of the list of arrays is defined as the sum ∑ni=1minmij=1ai,j∑i=1nminj=1miai,j. In other words, for each array, we find the minimum value in it and then sum up these values.
The goal of the game is to maximize the beauty of the list of arrays. Help Olya win this challenging game!
Input
Each test consists of multiple test cases. The first line contains a single integer tt (1≤t≤250001≤t≤25000) — the number of test cases. The description of test cases follows.
The first line of each test case contains a single integer nn (1≤n≤250001≤n≤25000) — the number of arrays in the list.
This is followed by descriptions of the arrays. Each array description consists of two lines.
The first line contains a single integer mimi (2≤mi≤500002≤mi≤50000) — the number of elements in the ii-th array.
The next line contains mimi integers ai,1,ai,2,…,ai,miai,1,ai,2,…,ai,mi (1≤ai,j≤1091≤ai,j≤109) — the elements of the ii-th array.
It is guaranteed that the sum of mimi over all test cases does not exceed 5000050000.
Output
For each test case, output a single line containing a single integer — the maximum beauty of the list of arrays that Olya can achieve.
Example
Input
Copy
3
2
2
1 2
2
4 3
1
3
100 1 6
3
4
1001 7 1007 5
3
8 11 6
2
2 9
Output
Copy
5 1 19
Note
In the first test case, we can move the integer 33 from the second array to the first array. Then the beauty is min(1,2,3)+min(4)=5min(1,2,3)+min(4)=5. It can be shown that this is the maximum possible beauty.
In the second test case, there is only one array, so regardless of the movements, the beauty will be min(100,1,6)=1min(100,1,6)=1.
解题说明:此题是一道模拟题,采用贪心算法,移动每行最小的到一起去,然后每行都保留倒数第二小的,最小的那个倒数第二小元素所在的行用来存放所有行中的最小数。
#include <bits/stdc++.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
vector<int> b, c;
for (int i = 0; i < n; i++)
{
int m;
cin >> m;
vector<int> a(m);
for (int j = 0; j < m; j++)
{
cin >> a[j];
}
sort(a.begin(), a.end());
b.push_back(a[0]);
c.push_back(a[1]);
}
sort(c.begin(), c.end());
long long sum = 0, cnt = 0;
for (int i = 0; i < n; i++)
{
sum += b[i];
if (i != 0)
{
cnt += c[i];
}
}
sort(b.begin(), b.end());
cnt += b[0];
if (n == 1)
{
cout << b[0] << endl;
}
else
{
cout << cnt<<endl;
}
}
return 0;
}