PTA 1113 Integer Set Partition (25 分)

简介: 代码如下

题目


Given a set of N (>1) positive integers, you are supposed to partition them into two disjoint sets A 1 and A 2 of n 1 and n 2 numbers, respectively. Let S 1 and S 2 denote the sums of all the numbers in A 1 and A 2 , respectively. You are supposed to make the partition so that ∣n 1 −n 2 ∣ is minimized first, and then ∣S 1 −S 2 ∣ is maximized.


Input Specification: Each input file contains one test case. For each case, the first line gives an integer N (2≤N≤10 5 ), and then N positive integers follow in the next line, separated by spaces. It is guaranteed that all the integers and their sum are less than 2 31 .


Output Specification: For each case, print in a line two numbers: ∣n 1 −n 2 ∣ and ∣S 1 −S 2 ∣, separated by exactly one space.


Sample Input 1:
10
23 8 10 99 46 2333 46 1 666 555
结尾无空行
Sample Output 1:
0 3611
结尾无空行
Sample Input 2:
13
110 79 218 69 3721 100 29 135 2 6 13 5188 85
结尾无空行
Sample Output 2:
1 9359
结尾无空行


解题思路


N = int(input())
inputList = list(map(int, input().split()))
# N = int("13")
# inputList = list(map(int, "110 79 218 69 3721 100 29 135 2 6 13 5188 85".split()))
# 排序后,从中间前后分割,然后求差值
inputList.sort()
fenge = N//2
sum1 = sum(inputList[:fenge])
sum2 = sum(inputList[fenge:])
# print(sum1,sum2)
# print(abs(sum1-sum2))
print(N%2,abs(sum1-sum2))


目录
相关文章
|
C++
【PAT甲级 - C++题解】1113 Integer Set Partition
【PAT甲级 - C++题解】1113 Integer Set Partition
251 0
【1113】Integer Set Partition (25分)
【1113】Integer Set Partition (25分) 【1113】Integer Set Partition (25分)
277 0
1113. Integer Set Partition (25) 简单题
#include #include #include #include using namespace std; int main() { int n; cin >> n; vector ...
930 0
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
751 2
|
存储 缓存 JavaScript
Set和Map有什么区别?
Set和Map有什么区别?
1007 1
|
编译器 C++ 容器
【c++丨STL】基于红黑树模拟实现set和map(附源码)
本文基于红黑树的实现,模拟了STL中的`set`和`map`容器。通过封装同一棵红黑树并进行适配修改,实现了两种容器的功能。主要步骤包括:1) 修改红黑树节点结构以支持不同数据类型;2) 使用仿函数适配键值比较逻辑;3) 实现双向迭代器支持遍历操作;4) 封装`insert`、`find`等接口,并为`map`实现`operator[]`。最终,通过测试代码验证了功能的正确性。此实现减少了代码冗余,展示了模板与仿函数的强大灵活性。
525 2
|
存储 JavaScript 前端开发
for...of循环在遍历Set和Map时的注意事项有哪些?
for...of循环在遍历Set和Map时的注意事项有哪些?
999 156
|
存储 算法 容器
set_map的实现+set/map加持秒杀高频算法题锻炼算法思维
`set`基于红黑树实现,支持有序存储、自动去重,增删查效率为O(logN)。通过仿函数可自定义排序规则,配合空间配置器灵活管理内存。不支持修改元素值,迭代器失效需注意。`multiset`允许重复元素。常用于去重、排序及查找场景。
|
存储 缓存 JavaScript
在JavaScript中,Set和Map的性能有什么区别?
在JavaScript中,Set和Map的性能有什么区别?
820 0
|
算法
你对Collection中Set、List、Map理解?
你对Collection中Set、List、Map理解?
391 18
你对Collection中Set、List、Map理解?