Codeforces Round #553 (Div. 2)D. Stas and the Queue at the Buffet

D. Stas and the Queue at the Buffet

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*(j-1)+b*(n-j)=j*(a-b)-a+b*n

对a-b的值排序就可以了。

#include "bits/stdc++.h"

using namespace std;
const int mod = 1e9 + 7;
struct node
{
    long long a,b;
    bool friend operator < (node a,node b)
    {
        return a.a-a.b>b.a-b.b;
    }
}a[100004];
int main() {
    long long n;
    scanf("%lld",&n);
    for (int i = 0; i < n; ++i) {
        scanf("%lld%lld",&a[i].a,&a[i].b);
    }
    sort(a,a+n);
    long long ans=0;
    for (int i = 0; i < n; ++i) {
        ans+=(a[i].a-a[i].b)*(i+1)-a[i].a+a[i].b*n;
    }
    printf("%lld\n",ans);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值