Codeforces 946A Partition(贪心)

题目链接: Partition

题意

将一个长度为 n n 的序列 a1,a2,,an 中的每个数字,分到两个序列 B B C 中,一个数字只能被分到一个序列,要求序列 B B 中所有数字的和减去序列 C 中所有数字的和的差最大,问最大的差是多少。

输入

第一行为一个整数 n (1n100) n   ( 1 ≤ n ≤ 100 ) ,第二行为 n n 个整数 a1,a2,,an (100ai100)

输出

输出序列 B B 中所有数字的和减去序列 C 中所有数字的和的差的最大值。

样例

输入
3
1 -2 0
输出
3
提示
我们可以令 B={1,0},C={2} B = { 1 , 0 } , C = { − 2 } 于是 sumB=1,sumC=2,sumBsumC=3 s u m B = 1 , s u m C = − 2 , s u m B − s u m C = 3
输入
6
16 23 16 15 42 8
输出
120
提示
B={16,23,16,15,42,8},C={} B = { 16 , 23 , 16 , 15 , 42 , 8 } , C = { } ,那么 sumB=120,sumC=0,BC=120 s u m B = 120 , s u m C = 0 , B − C = 120
题解

把所有正数都放到 B B 序列,所有负数都放到 C 序列,最后的结果等于 A A <script type="math/tex" id="MathJax-Element-46">A</script> 序列中所有数字绝对值的和。

过题代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <algorithm>
#include <functional>
#include <iomanip>
using namespace std;

#define LL long long
const int maxn = 200;
int n, num;

int main() {
    #ifdef LOCAL
        freopen("test.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
    #endif // LOCAL
    ios::sync_with_stdio(false);

    while(scanf("%d", &n) != EOF) {
        int ans = 0;
        for(int i = 0; i < n; ++i) {
            scanf("%d", &num);
            ans += abs(num);
        }
        printf("%d\n", ans);
    }

    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值