Codeforces 946A Partition 贪心

题目链接: Partition

题意

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

输入

第一行为一个整数 n   ( 1 n 100 ) ,第二行为 n 个整数 a 1 , a 2 , , a n   ( 100 a i 100 )

输出

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

样例

输入
3
1 -2 0
输出
3
提示
我们可以令 B = { 1 , 0 } , C = { 2 } 于是 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 = { } ,那么 s u m B = 120 , s u m C = 0 , B C = 120

题解

把所有正数都放到 B 序列,所有负数都放到 C 序列,最后的结果等于 A 序列中所有数字绝对值的和。

过题代码

#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;
}

猜你喜欢

转载自blog.csdn.net/CSDNjiangshan/article/details/81365545