time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of nn high school students numbered from 11 to nn. Initially, each student ii is on position ii. Each student ii is characterized by two numbers — aiai and bibi. Dissatisfaction of the person ii equals the product of aiai by the number of people standing to the left of his position, add the product bibi by the number of people standing to the right of his position. Formally, the dissatisfaction of the student ii, which is on the position jj, equals ai⋅(j−1)+bi⋅(n−j)ai⋅(j−1)+bi⋅(n−j).
The director entrusted Stas with the task: rearrange the people in the queue so that minimize the total dissatisfaction.
Although Stas is able to solve such problems, this was not given to him. He turned for help to you.
Input
The first line contains a single integer nn (1≤n≤1051≤n≤105) — the number of people in the queue.
Each of the following nn lines contains two integers aiai and bibi (1≤ai,bi≤1081≤ai,bi≤108) — the characteristic of the student ii, initially on the position ii.
Output
Output one integer — minimum total dissatisfaction which can be achieved by rearranging people in the queue.
Examples
input
Copy
3 4 2 2 3 6 1
output
Copy
12
input
Copy
4 2 4 3 3 7 1 2 3
output
Copy
25
input
Copy
10 5 10 12 4 31 45 20 55 30 17 29 30 41 32 7 1 5 5 3 15
output
Copy
1423
Note
In the first example it is optimal to put people in this order: (3,1,23,1,2). The first person is in the position of 22, then his dissatisfaction will be equal to 4⋅1+2⋅1=64⋅1+2⋅1=6. The second person is in the position of 33, his dissatisfaction will be equal to 2⋅2+3⋅0=42⋅2+3⋅0=4. The third person is in the position of 11, his dissatisfaction will be equal to 6⋅0+1⋅2=26⋅0+1⋅2=2. The total dissatisfaction will be 1212.
In the second example, you need to put people in this order: (3,2,4,13,2,4,1). The total dissatisfaction will be 2525.
题意:每个人有a,b。当一个人站在j的位置会产生 a⋅(j−1)+b⋅(n−j)的不满值,求如何分配使得所有的不满值之和最小?
这类题把 公式化下简,找到只有一个常量影响变量就行,类似找到一次线性函数的k即可。
ai⋅(j−1)+bi⋅(n−j)=(ai−bi)⋅j+(−ai+bi⋅n)
=bi*n-ai+(ai-bi)*j
也就是按照(ai-bi)从大到小排序分配位置即可。
/*?cf ????*/
#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=(b);++i)
#define rep2(i,a,b) for(int i=a;i<(b);++i)
#define per(i,a,b) for(int i=a;i>=(b);--i)
using namespace std;
typedef long long ll;
const ll mod=1e9+7;
ll gcd(ll a,ll b) { return b?gcd(b,a%b):a;}
ll powmod(ll a,ll b) {ll res=1;a%=mod;
for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
const int N=1e5+10;
int n;
struct node
{
ll x,y;
}a[N];
bool cmp(node a,node b)
{
return a.x-a.y>b.x-b.y;
}
int main()
{
cin>>n;
rep(i,1,n)
{
scanf("%lld%lld",&a[i].x,&a[i].y);
}
sort(a+1,a+1+n,cmp);
ll ans=0;
rep(i,1,n)
{
//printf("%d %d\n",a[i].x,a[i].y);
ans+=((i-1)*a[i].x+a[i].y*(n-i));
}
cout<<ans<<endl;
}