CF 1090 A. Company Merging

A. Company Merging

time limit per test1 second
memory limit per test512 megabytes
inputstandard input
outputstandard output
A conglomerate consists of n companies. To make managing easier, their owners have decided to merge all companies into one. By law, it is only possible to merge two companies, so the owners plan to select two companies, merge them into one, and continue doing so until there is only one company left.

But anti-monopoly service forbids to merge companies if they suspect unfriendly absorption. The criterion they use is the difference in maximum salaries between two companies. Merging is allowed only if the maximum salaries are equal.

To fulfill the anti-monopoly requirements, the owners can change salaries in their companies before merging. But the labor union insists on two conditions: it is only allowed to increase salaries, moreover all the employees in one company must get the same increase.

Sure enough, the owners want to minimize the total increase of all salaries in all companies. Help them find the minimal possible increase that will allow them to merge companies into one.

Input
The first line contains a single integer n — the number of companies in the conglomerate (1≤n≤2⋅105). Each of the next n lines describes a company.

A company description start with an integer mi — the number of its employees (1≤mi≤2⋅105). Then mi integers follow: the salaries of the employees. All salaries are positive and do not exceed 109.

The total number of employees in all companies does not exceed 2⋅105.

Output
Output a single integer — the minimal total increase of all employees that allows to merge all companies.

Example
inputCopy
3
2 4 3
2 2 1
3 1 1 1
outputCopy
13
Note
One of the optimal merging strategies is the following. First increase all salaries in the second company by 2, and merge the first and the second companies. Now the conglomerate consists of two companies with salaries [4,3,4,3] and [1,1,1]. To merge them, increase the salaries in the second of those by 3. The total increase is 2+2+3+3+3=13.

瞎胡翻译:合并公司,有n个公司,每个公司有m个员工,两个公司个最高工资必须相同才能合并,可以给员工涨工资,但是工资不能降,而且所有的员工必须一起涨
蜜汁思路:本来以为是哈夫曼树,又仔细一想,任何员工都会跟着初始公司的最高工资一起涨,所以谁先和谁合并最后的结果就是一样的。

需要注意的是需要用long long 类型。先交的两次提示的都是时间超时,我以为是思路错了,后来又想了想,看看怎么优化一下,发现数组开小了。。。加了个0就过了,啊太阳。总得来说,不难。

#include<stdio.h>
#define Max(a,b) (a)>(b)?(a):(b)
struct p{
	long long max;
	long long l;
};
int main()
{
	struct p a[200005];
	long long n;
	long long i;
	long long maxNum = 0;
	scanf("%lld",&n);
	long long m;
	for(i=0;i<n;i++){
		scanf("%lld",&m);
		a[i].l = m;
		a[i].max = 0;
		int j;
		long long num;
		for(j=0;j<m;j++){
			scanf("%lld",&num);
			a[i].max = Max(a[i].max,num);
			maxNum = Max(maxNum,num);
		}
	}
	long long sum = 0;
	for(i=0;i<n;i++){
		sum = sum + a[i].l * (maxNum - a[i].max);
	}
	printf("%lld",sum);
}

猜你喜欢

转载自blog.csdn.net/D_mengxin/article/details/84963849