python 结构体排序(自定义排序规则)

 

A.Stas and the Queue at the Buffet

题目描述:

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.

输入描述:

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 one integer — minimum total dissatisfaction which can be achieved by rearranging people in the queue.

测试样例:

样例输入 1

Copy

3

4 2

2 3

6 1

样例输出 1

Copy

12

样例输入 2

Copy

4

2 4

3 3

7 1

2 3

样例输出 2

Copy

25

样例输入 3

Copy

10

5 10

12 4

31 45

20 55

30 17

29 30

41 32

7 1

5 5

3 15

样例输出 3

Copy

1423

提示:

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.

n = int(input()) # 读入n
class xx:
    def __init__(self):
        self.x = 0
        self.y = 0
        self.z = 0
from functools import cmp_to_key # 引入模块
def cmp1(a, b):
    if a.z>b.z:
        return -1
    else:
        if a.z==b.z and a.y<b.y:
            return -1
        return 1

list1 = [] 
for i in range(0, n):
    list1.append(xx())
    list1[i].x, list1[i].y,= map(int,input().split())
    list1[i].z=list1[i].x-list1[i].y
list1.sort(key=cmp_to_key(cmp1)) # 按照cmp来排序
sum=0
for i in range(0, n):
    sum+=list1[i].x*i+list1[i].y*(n-i-1)
print(sum)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值