Codeforces 1151D

有n个人,第i个人站在位置j的情况下会产生一个值ai * (j-1) + bi (n-j ),j = 1,2,…,n,问怎样安排使得n个值之和最小。
将式子变形,得 (ai - bi) * j + bi * n - ai ;
可知每个人都会产生一个值 为 bi * n - ai,该值与这个人所要站得位置无关。
而 ai bi 是已知的,问题就转变为一个非常熟悉的贪心问题了

#include<bits/stdc++.h>
using namespace std;
#define forn(i,n) for(int i = 0;i<int(n);i++)
typedef long long LL;
int n;
int a[101010],b[101010],c[101010];
LL ans;
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	//freopen("data.in","r",stdin);
	//freopen("data.out","w",stdout);
	cin>>n;
	for(int i = 0;i<n;i++) {
		cin>>a[i]>>b[i];
		ans += (LL)b[i] * n - a[i];
		c[i] = a[i] - b[i]; 
	}
	sort(c,c+n);
	for(int i = 0 ;i<n;i++){
		ans += (LL)c[n-1-i] * (i+1);
	}
	cout<<ans;
	return 0; 
} 

猜你喜欢

转载自blog.csdn.net/winhcc/article/details/89404256
今日推荐